使用RestTemplate做这件事非常简单
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;@SpringBootApplicationpublic class Application implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String args[]) { SpringApplication.run(Application.class); } @Override public void run(String... args) throws Exception { RestTemplate restTemplate = new RestTemplate(); Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); }}
在日常的工作中我们返回的结果通常是一个Wrapper,含有一个泛型属性来表示真正的业务对象。这就要用到ParameterizedTypeReference
代码就成了这样了
@Override public void run(String... args) throws Exception { RestTemplate restTemplate = new RestTemplate(); ResponseWrapperquote = restTemplate.exchange("http://gturnquist-quoters.cfapps.io/api/random", HttpMethod.GET, null, new ParameterizedTypeReference >() {}); log.info(quote.toString()); }