Spring RestTemplate.postForEntity()

By Arvind Rai, 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.

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 the postForEntity method declaration from Spring doc.
ResponseEntity<T> postForEntity(URI url, Object request, Class<T> responseType) 
url: The URL to post the request.
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();
	}
} 
Find the web service that will serve the request.
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);
	}
} 
Employee.java
package com.concretepage.domain;
public class Employee {
	private int empId;
	private String name;
	private String city;
        //Getters and Setters
} 
EmployeeService.java
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());
	}
} 
Output
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) 
In this case our Employee class will change to support XML.
@XmlRootElement
public class Employee { 
------
} 

4. postForEntity() with URI Variables as Map

Find the postForEntity method declaration from Spring doc with URI variables as Map.
ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Map<String,?> uriVariables) 
uriVariables: A 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());
} 
Find the web service that will serve the request.
@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);
} 
We can see that @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 the postForEntity method declaration from Spring doc with URI variables as object varargs.
ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables) 
uriVariables: This is the object variable arguments to map URI template.

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());
} 
Server side code will be same as given above.
@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 
Now run RestClientUtil as Java Application.

7. Reference

Spring RestTemplate

8. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us