Home  >  Spring 5

Spring RestTemplate.postForObject()

By Arvind Rai, April 17, 2020
This page will walk through Spring RestTemplate.postForObject() method example. 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. The postForObject method returns the converted object of the given response type.
Find the postForObject methods with variety of parameters.
a. URI + request + responseType
T postForObject(URI url, Object request, Class<T> responseType) 
url: The url as URI.
request: It is the payload object to post. We can also use HttpEntity as request object to add additional HTTP headers. It can also be null.
responseType: This is response type returned by postForObject method.
The postForObject method returns the converted object of given response type.

b. url + request + responseType + uriVariables as Map
T postForObject(String url, Object request, Class<T> responseType, Map<String,?> uriVariables) 
uriVariables: URI variables as Map.

c. url + request + responseType + uriVariables as Object Varargs
T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables) 
uriVariables: URI variables as Object Varargs.

Now we will discuss using postForObject in our code 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 postForObject()

Find the example to post data using postForObject method. Here we will post the object to given url.
public void addEmployeeDemo() throws URISyntaxException {
	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());		
} 
Find the output.
Id: 111 
In the above code we are posting HttpEntity object which contains payload and HTTP headers.
We can pass our payload directly to postForObject method if no specific headers need to set.
Employee employee = restTemplate.postForObject(uri, objEmp, Employee.class); 

Find the server code to serve the above requests. To access the payload we need to use @RequestBody annotation.
@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);
	}
} 
Find the Employee class used in the example.
public class Employee {
	private int empId;
	private String name;
	private String city;
        //Setters and Getters
} 
Find the service.
@Service
public class EmployeeService {
	public void addEmployee(Employee emp) {
		emp.setEmpId(111);
		System.out.println("Name: " + emp.getName());
		System.out.println("City: " + emp.getCity());
	}
} 

4. URI Variables as Map

To post data with URI template using postForObject method, we can pass a Map as URI variables that will expand on URI template.
String url = "http://localhost:8080/employee/{profile}/{tech}";

Map<String, String> map = new HashMap<>();
map.put("profile", "Developer");
map.put("tech", "Java");

Employee employee = restTemplate.postForObject(url, httpEntity, Employee.class, map); 
In server side to access URI variables, we use @PathVariable annotation.
@PostMapping(value = "employee/{profile}/{tech}")
public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee, @PathVariable("profile") String profile,
			@PathVariable("tech") String technology, UriComponentsBuilder builder) {
  ------
} 

5. URI Variables as Object Varargs

For URI variables we can use Object Varargs as following.
String url = "http://localhost:8080/employee/{profile}/{tech}";

String profile = "Developer";
String technology = "Java";

Employee employee = restTemplate.postForObject(url, httpEntity, Employee.class, profile, technology); 
Server 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








©2020 concretepage.com | Privacy Policy | Contact Us