How to set the headers and body for RestTemplate?

To set request headers and body in RestTemplate, you can use the exchange() method to send an HTTP request. By creating a HttpEntity object, you can set the request headers and body, and pass it as a parameter to the exchange() method. Here is an example code:

RestTemplate restTemplate = new RestTemplate();

// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

// 设置请求体
String requestBody = "{\"key1\": \"value1\", \"key2\": \"value2\"}";

// 创建HttpEntity对象,设置请求头和请求体
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

// 发送POST请求
ResponseEntity<String> responseEntity = restTemplate.exchange("http://api.example.com", HttpMethod.POST, requestEntity, String.class);

String responseBody = responseEntity.getBody();
System.out.println(responseBody);

In the code above, we start by creating a RestTemplate object. Then, we set the request headers and body, and create an HttpEntity object. Finally, we use the exchange() method to send a POST request and obtain the response body.

bannerAds