【前言】REST教程第二篇,这里的“消费”指“解析、渲染”的意思。原文链接 http://spring.io/guides/gs/consuming-rest/
【目标】在这里,你将使用REST模板从Facebook图像API:http://graph.facebook.com/pivotalsoftware检索公司网页数据
【准备工作】和第一篇一样
<span style="font-size:14px;"> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> </dependencies></span>
package hello; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Page { private String name; private String about; private String phone; private String website; public String getName() { return name; } public String getAbout() { return about; } public String getPhone() { return phone; } public String getWebsite() { return website; } }这就是一个很简单的Java类,有一些属性和getter,唯一不同的是有一个注解@JsonIgnoreProperties,表示忽略(REST的Json响应页中)没有绑定到这个类的属性。
package hello; import org.springframework.web.client.RestTemplate; public class Application { public static void main(String args[]) { RestTemplate restTemplate = new RestTemplate(); Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class); System.out.println("Name: " + page.getName()); System.out.println("About: " + page.getAbout()); System.out.println("Phone: " + page.getPhone()); System.out.println("Website: " + page.getWebsite()); } }
Name: Pivotal About: At Pivotal, our mission is to enable customers to build a new class of applications, leveraging big and fast data, and do all of this with the power of cloud independence. Phone: 650-286-8012 Website: http://www.gopivotal.com【小结】掌握RESTTemplate对象的getForObject()方法,可以看看doc,应该还有其他方法。 注解@JsonIgnoreProperties在bean中的使用。