Consuming a RESTful Web Service
目标:
使用Spring提供的RestTemplate从以下站点
http://gturnquist-quoters.cfapps.io/api/random
获取WebService返回的信息
信息以json格式随机返回
格式如下:
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}
创建接收json数据的domain类:Quote和Value
package hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
package hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {
private Long id;
private String quote;
public Value() {
}
public Long getId() {
return this.id;
}
public String getQuote() {
return this.quote;
}
public void setId(Long id) {
this.id = id;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public String toString() {
return "Value{" +
"id=" + id +
", quote='" + quote + '\'' +
'}';
}
}
准备就绪,运行Application
package hello;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class Application implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
SpringApplication.run(Application.class);
}
public void run(String... strings) throws Exception {
RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
}
}
注:此处使用GET请求访问,当然也可以通过POST请求来获取。
测试:
控制台输出一下信息,表示测试成功:
Quote
{
type='success',
value=Value
{
id=6,
quote='It embraces convention over configuration, providing an experience on par with frameworks that excel at early stage development, such as Ruby on Rails.'
}
}
补充:
有关HTTP协议的请求方式:
- GET
通过请求URI得到资源 - POST
用于添加新的内容 - PUT
用于修改某个内容 - DELETE
删除某个内容 - CONNECT
用于代理进行传输,如使用SSL - OPTIONS
询问可以执行哪些方法 - PATCH
部分文档更改 - PROPFIND, (wedav)
查看属性 - PROPPATCH, (wedav)
设置属性 - MKCOL, (wedav)
创建集合(文件夹) - COPY, (wedav)
拷贝 - MOVE, (wedav)
移动 - LOCK, (wedav)
加锁 - UNLOCK (wedav)
解锁 - TRACE
用于远程诊断服务器 - HEAD
类似于GET, 但是不返回body信息,用于检查对象是否存在,以及得到对象的元数据