Spring REST Client with RestTemplate Consume RESTful Web Service Example for XML and JSON


In this tutorial we will learn how to use spring RestTemplate to consume RESTful Web Service. RestTemplate communicates HTTP server using RESTful principals. RestTemplate provides different methods to communicate via HTTP methods. The HTTP methods of RestTemplate accepts three variants as an argument. Two of them accepts URL template as string and URI variables as map. Third variant is that it accepts URI object. Find the description of RestTemplate methods which we are using in our example.

getForObject() : Use HTTP GET method to retrieve data.
exchange() : Executes the URI for the given HTTP method and returns the response.
headForHeaders() : Retrieves all headers.
getForEntity() : Use HTTP GET method with the given URL variables and returns ResponseEntity. delete() : Deletes the resources at the given URL.
put(): Creates the new resource for the given URL.
postForEntity(): Creates a news resource using HTTP POST method.
optionsForAllow() : Returns the allow header for the given URL.

We will use these methods in our example with different scenarios. We will show the demo to consume JSON and XML both.

Required Jars :- Add below jars to project class Path.
  • commons-logging-1.2.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar

Get XML / JSON representation in String format

RestTemplate getForObject()

final String uri = "http://localhost:8080/SpringRESTExample/rest/Employees";
 RestTemplate restTemplate = new RestTemplate();
 String result = restTemplate.getForObject(uri, String.class); 
 System.out.println(result);

Using custom HTTP Headers with RestTemplate

RestTemplate exchange()

final String uri = "http://localhost:8080/SpringRESTExample/rest/Employees";
 RestTemplate restTemplate = new RestTemplate();
 HttpHeaders headers = new HttpHeaders();
 headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
 HttpEntity<String> entity = new
HttpEntity<String>("parameters", headers);
 ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET,
entity, String.class);
 System.out.println(result);

Get data as mapped object

final String uri = "http://localhost:8080/SpringRESTXMLExample/employees";
 RestTemplate restTemplate = new RestTemplate();
 EmployeeList result = restTemplate.getForObject(uri, EmployeeList.class);
 System.out.println(result.getEmployees().get(0).getFirstName());

Java Bean used in Example

package com.tutorialsdesk.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;

@XmlRootElement (name = "employee")
@XmlAccessorType(XmlAccessType.NONE)
public class Employee implements Serializable{

 private static final long serialVersionUID = 5088863992478607917L;

 @XmlAttribute
 private Integer id;
 
 @XmlElement
 private String firstName;
 
 @XmlElement
 private String lastName;
 
 @XmlElement
 private String email;

 public Employee(Integer id, String firstName, String lastName, String email) {
 super();
 this.id = id;
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }

 public Employee() {
 super();
 // TODO Auto-generated constructor stub
 }

 public Integer getId() {
 return id;
 }

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

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastName() {
 return lastName;
 }

 public void setLastName(String lastName) {
 this.lastName = lastName;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public static long getSerialversionuid() {
 return serialVersionUID;
 }

 @Override
 public String toString() {
 return "Employee [id=" + id + ", firstName=" + firstName
 + ", lastName=" + lastName + ", email=" + email + "]";
 }
 
 
}


package com.tutorialsdesk.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement (name="employees")
public class EmployeeList implements Serializable{

 private static final long serialVersionUID = -7565600226888520442L;
 private List<Employee> employees = new ArrayList<Employee>();
 public List<Employee> getEmployees() {
 return employees;
 }
 
 public void setEmployees(List<Employee> employees) {
 this.employees = employees;
 }
}

Passing parameters in URL

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 Map<String, String> params = new HashMap<String, String>();
 params.put("id", "1");
 RestTemplate restTemplate = new RestTemplate();
 Employee result = restTemplate.getForObject(uri, Employee.class, params);
 System.out.println(result.getFirstName());

HTTP POST Method Example

RestTemplate postForObject()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/create";
 Employee newEmployee = new Employee(1, "Adam", "Gilly",
"test@email.com");
 RestTemplate restTemplate = new RestTemplate();
 Employee result = restTemplate.postForObject( uri, newEmployee, Employee.class);
 System.out.println(result);

HTTP PUT Method Example

RestTemplate put()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 Map<String, String> params = new HashMap<String, String>();
 params.put("id", "2");
 Employee updatedEmployee = new Employee(2, "New Name", "Gilly",
"test@email.com");
 RestTemplate restTemplate = new RestTemplate();
 restTemplate.put ( uri, updatedEmployee, params);

HTTP DELETE Method Example

RestTemplate delete()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 Map<String, String> params = new HashMap<String, String>();
 params.put("id", "2");
 RestTemplate restTemplate = new RestTemplate();
 restTemplate.delete ( uri, params );

RestTemplate headForHeaders()

RestTemplate restTemplate = new RestTemplate();
 String url = "http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 HttpHeaders httpHeaders = restTemplate.headForHeaders(url);
 System.out.println(httpHeaders.getContentLength());

RestTemplate optionsForAllow()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 RestTemplate restTemplate = new RestTemplate();
 Set<HttpMethod> entity= restTemplate.optionsForAllow(url);

RestTemplate getForEntity()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 RestTemplate restTemplate = new RestTemplate();
 Map<String, String> map = new HashMap<String, String>();
 map.put("district", "Varanasi");
 map.put("state", "100");
 ResponseEntity<Employee> personEntity = restTemplate.getForEntity(uri,
Employee.class, map);
 System.out.println("Name:"+personEntity.getBody().getName());
 System.out.println("Village:"+personEntity.getBody().getAddress().getVillage());

RestTemplate postForEntity()

final String uri =
"http://localhost:8080/SpringRESTXMLExample/employees/{id}";
 RestTemplate restTemplate = new RestTemplate();
 Map<String, String> map = new HashMap<String, String>();
 Employee newEmployee = new Employee(1, "Adam", "Gilly",
"test@email.com");
 map.put("district", "Varanasi");
 map.put("state", "100");
 ResponseEntity<Employee> personEntity = restTemplate.postForEntity(uri,null,
Employee.class, map);
 //ResponseEntity<Employee> personEntity =
restTemplate.postForEntity(uri,newEmployee, Employee.class, map);
 System.out.println("Name:"+personEntity.getBody().getName());


Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring REST Client with RestTemplate Consume RESTful Web Service Example for XML and JSON, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.