SpringBoot非官方教程 | 第十六篇:用restTemplate消費(fèi)服務(wù)

轉(zhuǎn)載請(qǐng)標(biāo)明出處:
http://blog.csdn.net/forezp/article/details/71023724
本文出自方志朋的博客

這篇文章主要介紹怎么用消費(fèi)一個(gè) Restful的web服務(wù)。我將用restTemplate去消費(fèi)一個(gè)服務(wù): http://gturnquist-quoters.cfapps.io/api/random.

構(gòu)架工程

創(chuàng)建一個(gè)springboot工程,去消費(fèi)RESTFUL的服務(wù)。這個(gè)服務(wù)是 http:///gturnquist-quoters.cfapps.io/api/random ,它會(huì)隨機(jī)返回Json字符串。
在Spring項(xiàng)目中,它提供了一個(gè)非常簡(jiǎn)便的類,叫RestTemplate,它可以很簡(jiǎn)便的消費(fèi)服務(wù)。

消費(fèi)服務(wù)

通過(guò)RestTemplate消費(fèi)服務(wù),需要先context中注冊(cè)一個(gè)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());
        };
    }

運(yùn)行程序,控制臺(tái)打?。?/p>

{
"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)秀文章推薦:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,273評(píng)論 6 342
  • SpringBoot非官方教程 | 終章:文章匯總 springboot非官方教程,可能最接近于官方的一個(gè)教程,大...
    方志朋閱讀 7,753評(píng)論 6 172
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,058評(píng)論 25 709
  • 人類最偉大的一面是具有真實(shí)的情感,感動(dòng)、激動(dòng)、幫助、感恩、傷心等等一切能觸動(dòng)心靈事物而引發(fā)的自然流露出的情緒...
    烽火煤閱讀 1,034評(píng)論 0 0

友情鏈接更多精彩內(nèi)容