轉(zhuǎn)載請標(biāo)明出處:
http://blog.csdn.net/forezp/article/details/71023724
本文出自方志朋的博客
這篇文章主要介紹怎么用消費一個 Restful的web服務(wù)。我將用restTemplate去消費一個服務(wù): http://gturnquist-quoters.cfapps.io/api/random.
構(gòu)架工程
創(chuàng)建一個springboot工程,去消費RESTFUL的服務(wù)倒脓。這個服務(wù)是 http:///gturnquist-quoters.cfapps.io/api/random 拄踪,它會隨機返回Json字符串。
在Spring項目中撵儿,它提供了一個非常簡便的類乘客,叫RestTemplate,它可以很簡便的消費服務(wù)淀歇。
消費服務(wù)
通過RestTemplate消費服務(wù)易核,需要先context中注冊一個RestTemplate bean。代碼如下:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
String quote = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random", String.class);
log.info(quote.toString());
};
}
運行程序浪默,控制臺打幽抵薄:
{
"type": "success",
"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."
}
}
參考資料
https://spring.io/guides/gs/consuming-rest/
源碼下載
https://github.com/forezp/SpringBootLearning
優(yōu)秀文章推薦:
- 更多springboot 教程:springBoot非官方教程 | 文章匯總
- 更多springcoud 教程:史上最簡單的 SpringCloud 教程 | 文章匯總