Home  >  Forum  >  Spring
Post New Query

RestTemplate postForObject() vs postForEntity() vs postForLocation()



Asked on November 13, 2020
What is difference between Spring RestTemplate postForObject(), postForEntity() and postForLocation() ?



Replied on November 19, 2020

RestTemplate.postForObject()

The postForObject method creates a new resource by posting the given object to given url or URI template using HTTP POST method. Request object is the payload to post and we can also use request as HttpEntity that helps to add additional HTTP headers. To post data on URI template using postForObject method, we can pass URI variables as Map and Object Varargs.

Find the method declarations.
1.
T postForObject(URI url, Object request, Class<T> responseType)
2.
T postForObject(String url, Object request, Class<T> responseType, Map<String,?> uriVariables) 
3.
T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables) 

Example:
Client code

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

URI uri = new URI("http://localhost:8080/employee");
Employee objEmp = new Employee();
objEmp.setName("Krishna");
objEmp.setCity("Noida");

HttpEntity<Employee> httpEntity = new HttpEntity<>(objEmp, headers);

RestTemplate restTemplate = new RestTemplate();
Employee employee = restTemplate.postForObject(uri, httpEntity, Employee.class);

System.out.println("Id: " + employee.getEmpId());

Server Code

@PostMapping(value = "employee")
public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee, UriComponentsBuilder builder) {

empService.addEmployee(employee);

HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/employee/{id}").buildAndExpand(employee.getEmpId()).toUri());
return new ResponseEntity<Employee>(employee, headers, HttpStatus.CREATED);
}



RestTemplate.postForEntity()

The postForEntity method creates new resource by posting the given object to the given URI template using HTTP POST method. The postForEntity method returns instance of ResponseEntity using which we can fetch the information about HTTP status, URI of newly created resource, response content body etc. The postForEntity method accepts URI template, object to post, response type.

Find the method declarations.
1.
ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType)
2.
ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Map<String,?> uriVariables) 
3.
ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables) 

Example:
Client code

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

String url = "http://localhost:8080/employee/{profile}/{tech}";
Employee objEmp = new Employee();
objEmp.setName("Krishna");
objEmp.setCity("Noida");

HttpEntity<Employee> requestEntity = new HttpEntity<>(objEmp, headers);

String profile = "Developer";
String technology = "Java";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Employee> responseEntity = restTemplate.postForEntity(url, requestEntity, Employee.class, profile, technology);

System.out.println("Status Code: " + responseEntity.getStatusCode());
System.out.println("Id: " + responseEntity.getBody().getEmpId());
System.out.println("Location: " + responseEntity.getHeaders().getLocation());

Server code
@PostMapping(value = "employee/{profile}/{tech}")
public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee, @PathVariable("profile") String profile,
@PathVariable("tech") String technology, UriComponentsBuilder builder) {
   ------




RestTemplate.postForLocation()

The postForLocation method creates a new resource by posting the given object to given URI template. The postForLocation method returns URI as the value of location header for newly created resource. The postForLocation sends data using HTTP POST method. The postForLocation method is useful when we want the only location header of newly created resource. 

Find the method declarations.
1.
URI postForLocation(String url, Object request, Map<String,?> uriVariables)
2.
URI postForLocation(String url, Object request, Object... uriVariables) 
3.
URI postForLocation(URI url, Object request)

Example:

Client code

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

String url = "http://localhost:8080/user/article/{cat}/{subCat}";

Map<String, String> map = new HashMap<>();
map.put("cat", "Spring Security UserDetailsService");
map.put("subCat", "Mahesh");

Article objArticle = new Article();
objArticle.setTitle("Spring Security UserDetailsService");
objArticle.setWriter("Mahesh");

HttpEntity<Article> requestEntity = new HttpEntity<>(objArticle, headers);

RestTemplate restTemplate = new RestTemplate();
URI uri = restTemplate.postForLocation(url, requestEntity, map);

System.out.println(uri.getPath());

Server code

@PostMapping(value = "article/{cat}/{subCat}")
public ResponseEntity<Void> addArticle(@RequestBody Article article, @PathVariable("cat") String category,
@PathVariable("subCat") String subCategory, UriComponentsBuilder builder) {

System.out.println("Category: " + category);
System.out.println("SubCategory: " + subCategory);

articleService.addArticle(article);

HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/article/{id}").buildAndExpand(article.getArticleId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}




Write Answer








©2021 concretepage.com | Privacy Policy | Contact Us