In this post under Spring RESTTemplate, I will show with example the purpose of “getForEntity” method available on “RestTemplate” class.
In our previous post, we have to make a GET http call, we used “getForObject” method available on “RestTemplate” class.
But “getForObject” method only returns response body and not the header information.
To get header information in addition to response body we need to take help of “getForEntity” method.
Below is the main class showing how to use the method.
Main class
package package8;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class Example8 {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "https://jsonplaceholder.typicode.com/posts/1";
ResponseEntity<Post> responseEntity = restTemplate.getForEntity(url, Post.class);
System.out.println("-------------------Headers---------------------");
for(String key : responseEntity.getHeaders().keySet()) {
System.out.println(key + ":" + responseEntity.getHeaders().get(key));
}
System.out.println(responseEntity.getHeaders().entrySet());
System.out.println("-------------------Status---------------------");
System.out.println(responseEntity.getStatusCode());
System.out.println("-------------------Body---------------------");
System.out.println(responseEntity.getBody());
}
}
In the above code at line 8 I created an instance of “RestTemplate” class.
At line 9 I defined a url string.
At line 10, I called “getForEntity” method passing the url and class object.
The return value is an instance of “ResponseEntity” class.
Using this instance in the subsequent code, I access the header, status, and body.
In this way we can use “getForEntity” method.