更改 Application.java文件
package com.example.kane; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class RestfulWebService1Application { private static final Logger log = LoggerFactory.getLogger(RestfulWebService1Application.class); public static void main(String[] args) { // 不启动Spring boot的application,直接运行RestTemplate // SpringApplication.run(RestfulWebService1Application.class, args); RestTemplate restTemplate = new RestTemplate(); System.out.println(Quote.class); Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); } /* 下面的代码官方说明是要管理RestTemplate,不明白什么意思 @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } @Bean public CommandLineRunner run(RestTemplate restTemplate) throws Exception { return args -> { Quote quote = restTemplate.getForObject( "http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); }; }*/ }定义一个Quote.java类
// Quote 定义的时候需要知道 restful api 返回的json对象都有什么属性,如果Quote中定义的属性在api中不存在那么将被复制为null, //我将官网的type属性更改为 type1属性后,结构显示type1:null package com.example.kane; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Quote { private String type1; private Value value; public Quote() { } public String getType() { return type1; } public void setType(String type) { this.type1 = type; } public Value getValue() { return value; } public void setValue(Value value) { this.value = value; } @Override public String toString() { return "Quote{" + "type='" + type1 + '\'' + ", value=" + value + '}'; } }定义Value.java
//value 与 quote相同,定义了这两个类 主要是返回的json对象中有这两个类 package com.example.kane; 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 + '\'' + '}'; } }上结果
20:59:39.613 [main] INFO com.example.kane.RestfulWebService1Application - Quote{type='null', value=Value{id=4, quote='Previous to Spring Boot, I remember XML hell, confusing set up, and many hours of frustration.'}}