设置请求头、请求体
1、POST、PUT请求设置请求头、请求体
@PostMapping("post_with_body_and_header")
public void postWithBodyAndHeader(@RequestBody(required = false) UserEntity requestBody) {
// 1.请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("headerName1", "headerValue1");
httpHeaders.add("headerName2", "headerValue2");
httpHeaders.add("headerName3", "headerValue3");
httpHeaders.add("Content-Type", "application/json"); // 传递请求体时必须设置
// 2.请求头 & 请求体
HttpEntity<String> fromEntity = new HttpEntity<>(JSONUtil.toJsonStr(requestBody), httpHeaders);
MessageBox responseBody = restTemplate.postForObject(INVOKE_URL + "/test/receive", fromEntity, MessageBox.class);
log.info("响应体:{}", JSONUtil.toJsonPrettyStr(responseBody));
}
2、其他请求设置请求头、请求体
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyRequestHeader", "MyValue");
HttpEntity requestEntity = new HttpEntity(requestHeaders);
HttpEntity<String> response = template.exchange(
"http://example.com/hotels/{hotel}",
HttpMethod.GET,
requestEntity,
String.class,
"42"
);
String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
String body = response.getBody();
标签:HttpEntity,请求,RestTemplate,HttpHeaders,add,new,httpHeaders
From: https://www.cnblogs.com/gongbw/p/18682595