RestTemplate的基本使用

2021-10-23 01:20:06 字數 671 閱讀 6519

resttemplate提供了多種便捷訪問遠端http服務的方法,是一種簡單便捷的訪問restful服務模組類,是spring提供的用於訪問rest服務的客戶端模板工具集。

使用resttemplate訪問restful介面非常的簡單粗暴無腦。(url,requestmap,responsebean.class)這三個引數分別代表rest請求位址、請求引數、http響應轉換被轉換成的物件型別。

返回物件為響應體中資料轉化成的物件,基本上可以理解為json

resttemplate.getforobject(url,class);

返回物件為responseentity物件,包含了響應中的一些重要資訊,比如響應頭、響應狀態碼、響應體等。

resttemplate.getforentity(url,class)

responseentityentity  = resttemplate.getforentity(url,commonresult.class);

if(entity.getstatuscode().is2xxsuccessful()) else

resttemplate.postforobject(url,object,class);

resttemplate.postforentity(url,object,class).getbody();

Spring中RestTemplate的使用

1 帶引數的get請求 請求url示例 http localhost 8080 test sendsms?phone 手機號 msg 簡訊內容 錯誤使用 autowired private restoperations restoperations public void test throws e...

對Spring 的RestTemplate進行包裝

spring的resttemplate及大地簡化了rest client的開發,但每次還要編寫大量的模板 不夠簡潔。我對他進行了一次包裝,採用介面來宣告rest介面,使用annotation對inte ce的方法進行標註。如下宣告乙個rest介面 介面必須繼承baserestclient,提供了乙個...

Spring中的RestTemplate原始碼分析

之前有一篇文章是分析的feign,這邊文章來分析spring中的resttemplate,下面還會有一篇來分析最新的webclient,當然這時後話,下面來具體看一下resttemplate的執行流程。get請求流程分析 getforobject 首先從get方法開始,傳入url,返回型別,引數即可...