In this post under Spring RestTemplate, I will show with example how to set request headers.
In our previous posts under Spring RestTemplate, I have covered the below methods
1) getForObject
2) postForObject
3) getForEntity
4) put
5) postForLocation
6) postForEntity
etc
None of these above methods provide you the option of setting request headers.
So to achieve this we use the method named “exchange” through which we can perform the above operations and in addition to that we can set request headers.
The “exchange” method takes below arguments
1) url
2) Method name like GET, POST, PUT etc
3) instance of “HttpEntity” that will body and headers.
4) response data type
5) optional uri variables
And returns an instance of “ResponseEntity” that has access to body, status, and response headers.
Below is the main class code showing how to use “exchange” method
Main class
package package9;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
public class Example9 {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://jsonplaceholder.typicode.com/posts/";
Post object = new Post();
object.setTitle("Don");
object.setBody("Hello");
object.setUserId(1);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Post> httpEntity = new HttpEntity<>(object, httpHeaders);
ResponseEntity<Post> postResponseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Post.class);
System.out.println(postResponseEntity.getStatusCode());
System.out.println(postResponseEntity.getBody());
}
}
In the above at line 9, I define a url
At line 10, I created a “Post” object that i will post to the server
At line 15, I created an instance of “HttpHeaders” set the content type
At line 17, I crated an instance of “HttpEntity” that will have the post data and headers both
At line 19, I call the “exchange” with url, operation type, instance of HttpEntity, and response data type.
In response I will get an instance of “ResponseEntity” through which we get the status and body and print it to console.
In this way we can set request headers.