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



In this page 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.

getForObject() for JSON

JSON input.
{
  "id" : 100,
  "name" : "Arvind Rai",
  "address" : {
    "village" : "Dhananjaypur",
    "district" : "Varanasi",
    "state" : "UP"
  }
}  
Client code.
RestTemplate restTemplate = new RestTemplate();
Person person = restTemplate.getForObject("http://localhost:8080/concretepage-1/villagerinfo.json", Person.class);
System.out.println("Name:    " + person.getName());
System.out.println("Village Name:    " + person.getAddress().getVillage());  

getForObject() for XML

XML input.
xml version="1.0" encoding="UTF-8" standalone="yes"?>
 xmlns:ns2="com.concretepage" id="100">
    XYZ
    ABCD
    100
  
Client code.
RestTemplate restTemplate = new RestTemplate();
Company company = restTemplate.getForObject("http://localhost:8080/concretepage-1/villagerinfo.xml", Company.class);
System.out.println("Company:    " + company.getCompanyName());
System.out.println("CEO:    " + company.getCeoName());  

Java Bean used in Example


Address.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
	private String village;
	private String district;
	private String state;
	public Address(){}
	public Address(String village, String district, String state){
		this.village = village;
		this.district = district;
		this.state = state;
	}
	public String getVillage() {
		return village;
	}
	public void setVillage(String village) {
		this.village = village;
	}
	public String getDistrict() {
		return district;
	}
	public void setDistrict(String district) {
		this.district = district;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
}  

Person.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
	private Integer id; 
	private String name;
  	private Address address;
  	public Person(){}
  	public Person(Integer id, String name, Address address){
  		this.id = id;
  		this.name = name;
  		this.address = address;
  	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
}  

Company.java
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="company-info", namespace="com.concretepage" )
@XmlAccessorType(XmlAccessType.NONE)
public class Company {
	@XmlAttribute(name="id")
	private Integer id;
	@XmlElement(name="company-name")
	private String companyName;
	@XmlElement(name="ceo-name")
	private String ceoName;
	@XmlElement(name="no-emp")
	private Integer noEmp;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCompanyName() {
		return companyName;
	}
	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}
	public String getCeoName() {
		return ceoName;
	}
	public void setCeoName(String ceoName) {
		this.ceoName = ceoName;
	}
	public Integer getNoEmp() {
		return noEmp;
	}
	public void setNoEmp(Integer noEmp) {
		this.noEmp = noEmp;
	}
}  

RestTemplate.exchange()

RestTemplate restTemplate = new RestTemplate();
URI uri = null;
try {
	uri = new URI("http://localhost:8080/concretepage-1/villagerinfo.json");
} catch (URISyntaxException e) {
	e.printStackTrace();
}
ResponseEntity<Person> personEntity = restTemplate.exchange(uri, HttpMethod.GET, null, Person.class);
System.out.println("Name:"+personEntity.getBody().getName());
System.out.println("Village:"+personEntity.getBody().getAddress().getVillage());   

RestTemplate.headForHeaders()

RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/concretepage-1/villagerinfo.json";
HttpHeaders httpHeaders = restTemplate.headForHeaders(url);
System.out.println(httpHeaders.getContentLength());  

RestTemplate.getForEntity()

Web Service code.
@RequestMapping("/fetch/{district}/{state}")
public Person getPersonDetail(@PathVariable(value = "district") String district,
                                    @PathVariable(value = "state") String state) {
	System.out.println("Fetch: District:"+ district+ " State:"+ state);
	Address address = new Address("Dhananjaypur",district, state);
	return new Person(100,"Ram", address);
}   
Client code.
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/spring-rest-1/data/fetch/{district}/{state}";
Map<String, String> map = new HashMap<String, String>();
map.put("district", "Varanasi");
map.put("state", "100");
ResponseEntity<Person> personEntity = restTemplate.getForEntity(url, Person.class, map);
System.out.println("Name:"+personEntity.getBody().getName());
System.out.println("Village:"+personEntity.getBody().getAddress().getVillage());   

RestTemplate.delete()

Web Service Code.
@RequestMapping("/delete/{district}/{state}")
public void deleteData(@PathVariable(value = "district") String district,
                        @PathVariable(value = "state") String state) {
        System.out.println("Delete: District:"+ district+ "State:"+ state);
}  
Client code.
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/spring-rest-1/data/delete/{district}/{state}";
Map<String, String> map = new HashMap<String, String>();
map.put("district", "Bhadohi");
map.put("state", "up");
restTemplate.delete(url, map);  

RestTemplate.put()

Web Service code.
@RequestMapping("/save/{id}/{name}")
public void saveData(@PathVariable(value = "id") String id,
                                    @PathVariable(value = "name") String name) {
        System.out.println("Save: Id:"+ id+ " Name:"+ name);
}  
Client code.
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/spring-rest-1/data/save/{id}/{name}";
Map<String, String> map = new HashMap<String, String>();
map.put("id", "100");
map.put("name", "Ram");
restTemplate.put(url, null, map);   

RestTemplate.postForEntity()

RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/spring-rest-1/data/postinfo/{id}/{name}";
Map<String, String> map = new HashMap<String, String>();
map.put("id", "111");
map.put("name", "Shyam");
ResponseEntity<Person> entity= restTemplate.postForEntity(url, null, Person.class, map);
System.out.println(entity.getBody().getName());  

RestTemplate.optionsForAllow()

RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/spring-rest-1/data/info";
Set<HttpMethod> entity= restTemplate.optionsForAllow(url);   

Download Complete Source Code

spring-rest-client-resttemplate-consume-restful-web-service-example-xml-json.zip

你可能感兴趣的:(spring)