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

转载地址:http://www.concretepage.com/spring/spring-mvc/spring-rest-client-resttemplate-consume-restful-web-service-example-xml-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"?>
<ns2:company-info xmlns:ns2="com.concretepage" id="100">
    <company-name>XYZ</company-name>
    <ceo-name>ABCD</ceo-name>
    <no-emp>100</no-emp>
</ns2:company-info>  
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值