本篇文章将介绍使用Spring来建立RESTful的Web Service。
我们通过一个例子来说明这篇文章:这个例子将会使用Spring的RestTemplate来从Facebook的提供的API中获取一些信息。然后对这些信息进行一些处理。Facebook的API为:
http://graph.facebook.com/gopivotal
其实在这个例子中,这个API只是为了掩饰用,并没有特别的含义。这个例子也只是为了说明从一个在线的接口中获取一些数据并进行处理。
当我们通过浏览器或者curl请求这个路径的时候会返回数据格式为:
{
"id": "161112704050757",
"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. ",
"app_id": "0",
"can_post": false,
"category": "Internet/software",
"checkins": 0,
"cover": {
"cover_id": 163344023827625,
"source": "http://sphotos-d.ak.fbcdn.net/hphotos-ak-frc1/s720x720/554668_163344023827625_839302172_n.png",
"offset_y": 0,
"offset_x": 0
},
"founded": "2013",
"has_added_app": false,
"is_community_page": false,
"is_published": true,
"likes": 126,
"link": "https://www.facebook.com/gopivotal",
"location": {
"street": "1900 South Norfolk St.",
"city": "San Mateo",
"state": "CA",
"country": "United States",
"zip": "94403",
"latitude": 37.552261,
"longitude": -122.292152
},
"name": "Pivotal",
"phone": "650-286-8012",
"talking_about_count": 15,
"username": "gopivotal",
"website": "http://www.gopivotal.com",
"were_here_count": 0
}
的数据。但是我们只需要其中的一些很少的信息。在这种情况下我们就可以使用Spring的RestTemplate来帮助我们完成这个工作:
我们通过一个Model来定义我们需要的一些属性:
package hello;
import org.codehaus.jackson.annotate.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;
}
}
使用@JsonIgnoreProperties注解来忽略一些我们我们不需要的属性。
然后我们就可以编写下面的方法来完成我们的工作:
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/gopivotal", 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());
}
}
因为我们在classpath中增加了 Jackson 库,所以spring就可以使用 message converter将JSON对象映射为我们定义的model。
虽然在这快我们使用的是get请求,但是RestTemplate也支持POST,PUT,DELETE请求。
最后运行我们的程序,数据结果如下:
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