Spring Rest Template Post JSON example - Java @ Desk

Friday, September 1, 2017

Spring Rest Template Post JSON example

Spring Rest Template Post JSON example

Spring RestTemplate - org.springframework.web.client.RestTemplate helps in accessing the third party Rest Services. The methods used to get or post the data is similar to what we have learned in the past.

Following are the important methods to get/post/put/delete the data headForHeaders(), getForObject(), postForObject(), put() and delete() etc.

Below example is the rest service that consumes the JSON and produces the JSON itself. The service produces and consumes the Person Object as shown below
package com.pojo;

public class Person {

 private String id;
 
 private String name;
 
 private String address;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }
}


Here is the Rest Service method that consumes the Person object in JSON format and returns the Person JSON object
@RequestMapping(value = "/person", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> createEmployee(@RequestBody Person person) {
 return new ResponseEntity<Person>(person, HttpStatus.OK);
}


Here is the Rest Client Code using RestTemplate class to give a call to the Rest Service
private static void createEmployee() {
 final String uri = "http://localhost:8080/resttemplate/person";

 Person person = new Person(1, "Adam", "Mumbai");

 RestTemplate restTemplate = new RestTemplate();
 Person person = restTemplate.postForObject(uri, person, Person.class);

 System.out.println(person);
}






No comments:

Post a Comment