Spring RestTemplate.postForEntity()
April 09, 2020
This page will walk through Spring RestTemplate.postForEntity
method example. 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. We can also pass path variables as Map
and object variable arguments to this method.
Now let us discuss the
postForEntity
method examples in detail.
Contents
1. Technologies Used
Find the technologies being used in our example.1. Java 11
2. Spring 5.2.5.RELEASE
3. Spring Boot 2.2.6.RELEASE
4. Maven 3.5.2
2. Maven Dependencies
Find the Maven dependencies to run the example.<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
3. Using postForEntity()
Find thepostForEntity
method declaration from Spring doc.
ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType)
request: The object to be posted.
responseType: The type of response body.
Find the client code using
postForEntity
.
RestClientUtil.java
package com.concretepage.client; import java.net.URI; import java.net.URISyntaxException; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import com.concretepage.domain.Employee; public class RestClientUtil { public void addEmployeeDemo() throws URISyntaxException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); URI url = new URI("http://localhost:8080/employee"); Employee objEmp = new Employee(); objEmp.setName("Krishna"); objEmp.setCity("Noida"); HttpEntity<Employee> requestEntity = new HttpEntity<>(objEmp, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<Employee> responseEntity = restTemplate.postForEntity(url, requestEntity, Employee.class); System.out.println("Status Code: " + responseEntity.getStatusCode()); System.out.println("Id: " + responseEntity.getBody().getEmpId()); System.out.println("Location: " + responseEntity.getHeaders().getLocation()); } public static void main(String args[]) throws URISyntaxException { RestClientUtil util = new RestClientUtil(); util.addEmployeeDemo(); } }
EmployeeController.java
package com.concretepage.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import com.concretepage.domain.Employee; import com.concretepage.service.EmployeeService; @RestController public class EmployeeController { @Autowired private EmployeeService empService; @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); } }
package com.concretepage.domain; public class Employee { private int empId; private String name; private String city; //Getters and Setters }
package com.concretepage.service; import org.springframework.stereotype.Service; import com.concretepage.domain.Employee; @Service public class EmployeeService { public void addEmployee(Employee emp) { emp.setEmpId(111); System.out.println("Name: " + emp.getName()); System.out.println("City: " + emp.getCity()); } }
Status Code: 201 CREATED Id: 111 Location: http://localhost:8080/employee/111
In above example, the request content type is set to JSON type. We can set to XML type as following.
headers.setContentType(MediaType.APPLICATION_XML)
Employee
class will change to support XML.
@XmlRootElement public class Employee { ------ }
4. postForEntity() with URI Variables as Map
Find thepostForEntity
method declaration from Spring doc with URI variables as Map
.
ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Map<String,?> uriVariables)
Map
containing variables to expand the URI template.
Find the client code with
postForEntity
method. Here we will use URI variables in our URI template. We will create a Map
in which key will be URI variable and value will be value of URI variable.
public void addEmployeeDemo() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); String url = "http://localhost:8080/employee/{profile}/{tech}"; Map<String, String> map = new HashMap<>(); map.put("profile", "Developer"); map.put("tech", "Java"); Employee objEmp = new Employee(); objEmp.setName("Krishna"); objEmp.setCity("Noida"); HttpEntity<Employee> requestEntity = new HttpEntity<>(objEmp, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<Employee> responseEntity = restTemplate.postForEntity(url, requestEntity, Employee.class, map); System.out.println("Status Code: " + responseEntity.getStatusCode()); System.out.println("Id: " + responseEntity.getBody().getEmpId()); System.out.println("Location: " + responseEntity.getHeaders().getLocation()); }
@PostMapping(value = "employee/{profile}/{tech}") public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee, @PathVariable("profile") String profile, @PathVariable("tech") String technology, UriComponentsBuilder builder) { System.out.println("Profile: " + profile); System.out.println("Technology: " + technology); 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); }
@PostMapping
is mapping URI with URI variables. To access these variables, we need to use @PathVariable
annotation.
5. postForEntity() with URI Variables as Object Varargs
Find thepostForEntity
method declaration from Spring doc with URI variables as object varargs.
ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)
Find the client code with
postForEntity
method. Here we are passing URI variables as object variable arguments (varargs).
public void addEmployeeDemo() { 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()); }
@PostMapping(value = "employee/{profile}/{tech}") public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee, @PathVariable("profile") String profile, @PathVariable("tech") String technology, UriComponentsBuilder builder) { ------ }
6. Run Application
Download the project and run the following command from root folder of the project using command prompt.mvn spring-boot:run
RestClientUtil
as Java Application.