一. 什么是resttemplate
spring's central class for synchronous client-side http access.
it simplifies communication with http servers, and enforces restful principles.
it handles http connections, leaving application code to provide urls(with possible template variables) and extract results.
上面這段是resttemplate類中的簡單介紹,resttemplate是spring3.0后開始提供的用于訪問 rest 服務的輕量級客戶端,相較于傳統的httpurlconnection、apache httpclient、okhttp等框架,resttemplate大大簡化了發起http請求以及處理響應的過程。本文關注resttemplate是如何使用的,暫不涉及內部的實現原理。
二.一個簡單的例子。
定義一個簡單的restful接口
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@restcontroller public class testcontroller { @requestmapping (value = "testpost" , method = requestmethod.post) public responsebean testpost( @requestbody requestbean requestbean) { responsebean responsebean = new responsebean(); responsebean.setretcode( "0000" ); responsebean.setretmsg( "succ" ); return responsebean; } } |
使用resttemplate訪問該服務
1
2
3
4
5
6
7
8
9
10
|
//請求地址 string url = "http://localhost:8080/testpost" ; //入參 requestbean requestbean = new requestbean(); requestbean.settest1( "1" ); requestbean.settest2( "2" ); requestbean.settest3( "3" ); resttemplate resttemplate = new resttemplate(); responsebean responsebean = resttemplate.postforobject(url, requestbean, responsebean. class ); |
從這個例子可以看出,使用resttemplate訪問restful接口非常的簡單粗暴無腦。(url, requestmap, responsebean.class)這三個參數分別代表 請求地址、請求參數、http響應轉換被轉換成的對象類型。
resttemplate方法的名稱遵循命名約定,第一部分指出正在調用什么http方法,第二部分指示返回的內容。本例中調用了resttemplate.postforobject方法,post指調用了http的post方法,object指將http響應轉換為您選擇的對象類型。還有其他很多類似的方法,有興趣的同學可以參考官方api。
三.手動指定轉換器(httpmessageconverter)
我們知道,調用reseful接口傳遞的數據內容是json格式的字符串,返回的響應也是json格式的字符串。然而resttemplate.postforobject方法的請求參數requestbean和返回參數responsebean卻都是java類。是resttemplate通過httpmessageconverter自動幫我們做了轉換的操作。
默認情況下resttemplate自動幫我們注冊了一組httpmessageconverter用來處理一些不同的contenttype的請求。
如stringhttpmessageconverter來處理text/plain;mappingjackson2httpmessageconverter來處理application/json;mappingjackson2xmlhttpmessageconverter來處理application/xml。
你可以在org.springframework.http.converter包下找到所有spring幫我們實現好的轉換器。
如果現有的轉換器不能滿足你的需求,你還可以實現org.springframework.http.converter.httpmessageconverter接口自己寫一個。詳情參考官方api。
選好了httpmessageconverter后怎么把它注冊到我們的resttemplate中呢。
1
2
3
4
5
6
7
|
resttemplate resttemplate = new resttemplate(); //獲取resttemplate默認配置好的所有轉換器 list<httpmessageconverter<?>> messageconverters = resttemplate.getmessageconverters(); //默認的mappingjackson2httpmessageconverter在第7個 先把它移除掉 messageconverters.remove( 6 ); //添加上gson的轉換器 messageconverters.add( 6 , new gsonhttpmessageconverter()); |
這個簡單的例子展示了如何使用gsonhttpmessageconverter替換掉默認用來處理application/json的mappingjackson2httpmessageconverter。
四.設置底層連接方式
要創建一個resttemplate的實例,您可以像上述例子中簡單地調用默認的無參數構造函數。這將使用java.net包中的標準java類作為底層實現來創建http請求。
但很多時候我們需要像傳統的httpclient那樣設置http請求的一些屬性。resttemplate使用了一種很偷懶的方式實現了這個需求,那就是直接使用一個httpclient作為底層實現......
1
2
3
4
5
6
7
8
|
//生成一個設置了連接超時時間、請求超時時間、異常最大重試次數的httpclient requestconfig config = requestconfig.custom().setconnectionrequesttimeout( 10000 ).setconnecttimeout( 10000 ).setsockettimeout( 30000 ).build(); httpclientbuilder builder = httpclientbuilder.create().setdefaultrequestconfig(config).setretryhandler( new defaulthttprequestretryhandler( 5 , false )); httpclient httpclient = builder.build(); //使用httpclient創建一個clienthttprequestfactory的實現 clienthttprequestfactory requestfactory = new httpcomponentsclienthttprequestfactory(httpclient); //clienthttprequestfactory作為參數構造一個使用作為底層的resttemplate resttemplate resttemplate = new resttemplate(requestfactory); |
五.設置攔截器(clienthttprequestinterceptor)
有時候我們需要對請求做一些通用的攔截設置,這就可以使用攔截器進行處理。攔截器需要我們實現org.springframework.http.client.clienthttprequestinterceptor接口自己寫。
舉個簡單的例子,寫一個在header中根據請求內容和地址添加令牌的攔截器。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class tokeninterceptor implements clienthttprequestinterceptor { @override public clienthttpresponse intercept(httprequest request, byte [] body, clienthttprequestexecution execution) throws ioexception { //請求地址 string checktokenurl = request.geturi().getpath(); //token有效時間 int tttime = ( int ) (system.currenttimemillis() / 1000 + 1800 ); //請求方法名 post、get等 string methodname = request.getmethod().name(); //請求內容 string requestbody = new string(body); //生成令牌 此處調用一個自己寫的方法,有興趣的朋友可以自行google如何使用ak/sk生成token,此方法跟本教程無關,就不貼出來了 string token = tokenhelper.generatetoken(checktokenurl, tttime, methodname, requestbody); //將令牌放入請求header中 request.getheaders().add( "x-auth-token" ,token); return execution.execute(request, body); } } |
創建resttemplate實例的時候可以這樣向其中添加攔截器
1
2
3
|
resttemplate resttemplate = new resttemplate(); //向resttemplate中添加自定義的攔截器 resttemplate.getinterceptors().add( new tokeninterceptor()); |
六.總結
通過本章的講解,想必讀者初步的了解了如何使用resttemplate方便快捷的訪問restful接口。其實resttemplate的功能非常強大,作者也僅僅學了點皮毛。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/c9644755dd5e