Rest Template in Java
RestTemplate :
1) Why do we need RestTemplate?
==> To communicate with different services in single application.
Create Resttemplate object:
// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();
2) Different methods of RestTemplate.
exchange()
<http_method>ForEntity ex getForEntity(),postForEntity()
<http_method>ForObject ex getForObject(),postForObject()
HttpPost Api with parameters: Returns
PostForObject(url,request,classType); ResponseBody
PostForEntity(url,request,responseType); Response status,header,body
PostForLocation(url,request,responseType); Only Location of the created resources.
exchange(url,httpmethod,request,responseType);
execute(url,httpmethod,request,responseType);
To Posting Json data:
PostForObject(url,request,classType); ResponseBody
PostForEntity(url,request,responseType); Response status,header,body
PostForLocation(url,request,responseType); Only Location of the created resources.
Sending Header with RestTemplate
To send the request headers with the request ,we need to create an HtpEntity object,set Headers and post it to API.
To make a Post request with the JSON request body, we need to set the contentType request header to application/json.
Example
// request url
String url = "https://reqres.in/api/login";
// create headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// build the request
HttpEntity request = new HttpEntity(headers);
// send POST request
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
POST Request with Response Mapped to Java Object:
// request url
String url = "https://jsonplaceholder.typicode.com/posts";
// create an instance of RestTemplate
RestTemplate restTemplate = new RestTemplate();
// create headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// create a post object
Post post = new Post(101, 1, "Spring Boot 101",
"A powerful tool for building web apps.");
// build the request
HttpEntity<Post> request = new HttpEntity<>(post, headers);
// send POST request
ResponseEntity<Post> response = restTemplate.postForEntity(url, request, Post.class);
// check response
if (response.getStatusCode() == HttpStatus.CREATED) {
System.out.println("Post Created");
System.out.println(response.getBody());
} else {
System.out.println("Request Failed");
System.out.println(response.getStatusCode());
}
Hope you learned something new today.
Happy Learning :)
-------------------------------------------------------------------------------------------------------- Share this blog to spread the knowledge

Comments
Post a Comment