javascript
转: Springboot — 用更优雅的方式发HTTP请求(RestTemplate详解)
轉(zhuǎn)自:
Springboot — 用更優(yōu)雅的方式發(fā)HTTP請(qǐng)求(RestTemplate詳解) - Java知音號(hào) - 博客園RestTemplate是Spring提供的用于訪(fǎng)問(wèn)Rest服務(wù)的客戶(hù)端,RestTemplate提供了多種便捷訪(fǎng)問(wèn)遠(yuǎn)程Http服務(wù)的方法,能夠大大提高客戶(hù)端的編寫(xiě)效率。 我之前的HTTP開(kāi)發(fā)是用aphttps://www.cnblogs.com/javazhiyin/p/9851775.html
RestTemplate是Spring提供的用于訪(fǎng)問(wèn)Rest服務(wù)的客戶(hù)端,RestTemplate提供了多種便捷訪(fǎng)問(wèn)遠(yuǎn)程Http服務(wù)的方法,能夠大大提高客戶(hù)端的編寫(xiě)效率。
我之前的HTTP開(kāi)發(fā)是用apache的HttpClient開(kāi)發(fā),代碼復(fù)雜,還得操心資源回收等。代碼很復(fù)雜,冗余代碼多,稍微截個(gè)圖,這是我封裝好的一個(gè)post請(qǐng)求工具:
本教程將帶領(lǐng)大家實(shí)現(xiàn)Spring生態(tài)內(nèi)RestTemplate的Get請(qǐng)求和Post請(qǐng)求還有exchange指定請(qǐng)求類(lèi)型的實(shí)踐和RestTemplate核心方法源碼的分析,看完你就會(huì)用優(yōu)雅的方式來(lái)發(fā)HTTP請(qǐng)求。
1.簡(jiǎn)述RestTemplate
是Spring用于同步client端的核心類(lèi),簡(jiǎn)化了與http服務(wù)的通信,并滿(mǎn)足RestFul原則,程序代碼可以給它提供URL,并提取結(jié)果。默認(rèn)情況下,RestTemplate默認(rèn)依賴(lài)jdk的HTTP連接工具。當(dāng)然你也可以 通過(guò)setRequestFactory屬性切換到不同的HTTP源,比如Apache HttpComponents、Netty和OkHttp。
RestTemplate能大幅簡(jiǎn)化了提交表單數(shù)據(jù)的難度,并且附帶了自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)的功能,但只有理解了HttpEntity的組成結(jié)構(gòu)(header與body),且理解了與uriVariables之間的差異,才能真正掌握其用法。這一點(diǎn)在Post請(qǐng)求更加突出,下面會(huì)介紹到。
該類(lèi)的入口主要是根據(jù)HTTP的六個(gè)方法制定:
此外,exchange和excute可以通用上述方法。
在內(nèi)部,RestTemplate默認(rèn)使用HttpMessageConverter實(shí)例將HTTP消息轉(zhuǎn)換成POJO或者從POJO轉(zhuǎn)換成HTTP消息。默認(rèn)情況下會(huì)注冊(cè)主mime類(lèi)型的轉(zhuǎn)換器,但也可以通過(guò)setMessageConverters注冊(cè)其他的轉(zhuǎn)換器。
其實(shí)這點(diǎn)在使用的時(shí)候是察覺(jué)不到的,很多方法有一個(gè)responseType 參數(shù),它讓你傳入一個(gè)響應(yīng)體所映射成的對(duì)象,然后底層用HttpMessageConverter將其做映射
| 1 2 | HttpMessageConverterExtractor<T> responseExtractor = ????????????????new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger); |
HttpMessageConverter.java源碼:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public interface HttpMessageConverter<T> { ????????//指示此轉(zhuǎn)換器是否可以讀取給定的類(lèi)。 ????boolean canRead(Class<?> clazz, @Nullable MediaType mediaType); ????????//指示此轉(zhuǎn)換器是否可以寫(xiě)給定的類(lèi)。 ????boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType); ????????//返回List<MediaType> ????List<MediaType> getSupportedMediaTypes(); ????????//讀取一個(gè)inputMessage ????T read(Class<? extends T> clazz, HttpInputMessage inputMessage) ????????????throws IOException, HttpMessageNotReadableException; ????????//往output message寫(xiě)一個(gè)Object ????void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) ????????????throws IOException, HttpMessageNotWritableException; } |
在內(nèi)部,RestTemplate默認(rèn)使用SimpleClientHttpRequestFactory和DefaultResponseErrorHandler來(lái)分別處理HTTP的創(chuàng)建和錯(cuò)誤,但也可以通過(guò)setRequestFactory和setErrorHandler來(lái)覆蓋。
2.get請(qǐng)求實(shí)踐
2.1.getForObject()方法
| 1 2 3 | public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables){} public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) public <T> T getForObject(URI url, Class<T> responseType) |
getForObject()其實(shí)比getForEntity()多包含了將HTTP轉(zhuǎn)成POJO的功能,但是getForObject沒(méi)有處理response的能力。因?yàn)樗玫绞值木褪浅尚偷膒ojo。省略了很多response的信息。
2.1.1 POJO:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Notice { ????private int status; ????private Object msg; ????private List<DataBean> data; } public? class DataBean { ??private int noticeId; ??private String noticeTitle; ??private Object noticeImg; ??private long noticeCreateTime; ??private long noticeUpdateTime; ??private String noticeContent; } |
示例:2.1.2 不帶參的get請(qǐng)求
????| 1 2 3 4 5 6 7 8 9 10 | /** ?????* 不帶參的get請(qǐng)求 ?????*/ ????@Test ????public void restTemplateGetTest(){ ????????RestTemplate restTemplate = new RestTemplate(); ????????Notice notice = restTemplate.getForObject("http://xxx.top/notice/list/1/5" ????????????????, Notice.class); ????????System.out.println(notice); ????} |
控制臺(tái)打印:
| 1 2 3 4 5 6 7 | INFO 19076 --- [?????????? main] c.w.s.c.w.c.HelloControllerTest????????? : Started HelloControllerTest in 5.532 seconds (JVM running for 7.233) Notice{status=200, msg=null, data=[DataBean{noticeId=21, noticeTitle='aaa', noticeImg=null, noticeCreateTime=1525292723000, noticeUpdateTime=1525292723000, noticeContent='<p>aaa</p>'}, DataBean{noticeId=20, noticeTitle='ahaha', noticeImg=null, noticeCreateTime=1525291492000, noticeUpdateTime=1525291492000, noticeContent='<p>ah.......' |
示例:2.1.3 帶參數(shù)的get請(qǐng)求1
Notice?notice?=?restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}",?Notice.class,1,5);明眼人一眼能看出是用了占位符{1}。
示例:2.1.4 帶參數(shù)的get請(qǐng)求2
??| 1 2 3 4 5 | Map<String,String> map = new HashMap(); ????????map.put("start","1"); ????????map.put("page","5"); ????????Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/" ????????????????, Notice.class,map); |
明眼人一看就是利用map裝載參數(shù),不過(guò)它默認(rèn)解析的是PathVariable的url形式。
2.2 getForEntity()方法
| 1 2 3 | public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables){} public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables){} public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType){} |
與getForObject()方法不同的是返回的是ResponseEntity對(duì)象,如果需要轉(zhuǎn)換成pojo,還需要json工具類(lèi)的引入,這個(gè)按個(gè)人喜好用。不會(huì)解析json的可以百度FastJson或者Jackson等工具類(lèi)。然后我們就研究一下ResponseEntity下面有啥方法。
ResponseEntity、HttpStatus、BodyBuilder結(jié)構(gòu)
ResponseEntity.java
| 1 2 3 4 5 6 7 8 9 | public HttpStatus getStatusCode(){} public int getStatusCodeValue(){} public boolean equals(@Nullable Object other) {} public String toString() {} public static BodyBuilder status(HttpStatus status) {} public static BodyBuilder ok() {} public static <T> ResponseEntity<T> ok(T body) {} public static BodyBuilder created(URI location) {} ... |
HttpStatus.java
| 1 2 3 4 5 6 7 8 | public enum HttpStatus { public boolean is1xxInformational() {} public boolean is2xxSuccessful() {} public boolean is3xxRedirection() {} public boolean is4xxClientError() {} public boolean is5xxServerError() {} public boolean isError() {} } |
BodyBuilder.java
| 1 2 3 4 5 6 7 8 | public interface BodyBuilder extends HeadersBuilder<BodyBuilder> { ????//設(shè)置正文的長(zhǎng)度,以字節(jié)為單位,由Content-Length標(biāo)頭 ??????BodyBuilder contentLength(long contentLength); ????//設(shè)置body的MediaType 類(lèi)型 ??????BodyBuilder contentType(MediaType contentType); ????//設(shè)置響應(yīng)實(shí)體的主體并返回它。 ??????<T> ResponseEntity<T> body(@Nullable T body); } |
可以看出來(lái),ResponseEntity包含了HttpStatus和BodyBuilder的這些信息,這更方便我們處理response原生的東西。
示例:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | @Test public void rtGetEntity(){ ????????RestTemplate restTemplate = new RestTemplate(); ????????ResponseEntity<Notice> entity = restTemplate.getForEntity("http://fantj.top/notice/list/1/5" ????????????????, Notice.class); ????????HttpStatus statusCode = entity.getStatusCode(); ????????System.out.println("statusCode.is2xxSuccessful()"+statusCode.is2xxSuccessful()); ????????Notice body = entity.getBody(); ????????System.out.println("entity.getBody()"+body); ????????ResponseEntity.BodyBuilder status = ResponseEntity.status(statusCode); ????????status.contentLength(100); ????????status.body("我在這里添加一句話(huà)"); ????????ResponseEntity<Class<Notice>> body1 = status.body(Notice.class); ????????Class<Notice> body2 = body1.getBody(); ????????System.out.println("body1.toString()"+body1.toString()); ????} ?? statusCode.is2xxSuccessful()true entity.getBody()Notice{status=200, msg=null, data=[DataBean{noticeId=21, noticeTitle='aaa', ... body1.toString()<200 OK,class com.waylau.spring.cloud.weather.pojo.Notice,{Content-Length=[100]}> |
當(dāng)然,還有g(shù)etHeaders()等方法沒(méi)有舉例。
3. post請(qǐng)求實(shí)踐
同樣的,post請(qǐng)求也有postForObject和postForEntity。
| 1 2 3 4 5 | public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables) ????????????throws RestClientException {} public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables) ????????????throws RestClientException {} public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {} |
示例
我用一個(gè)驗(yàn)證郵箱的接口來(lái)測(cè)試。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | @Test public void rtPostObject(){ ????RestTemplate restTemplate = new RestTemplate(); ????String url = "http://47.xxx.xxx.96/register/checkEmail"; ????HttpHeaders headers = new HttpHeaders(); ????headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); ????MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); ????map.add("email", "844072586@qq.com"); ????HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ????ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class ); ????System.out.println(response.getBody()); } |
執(zhí)行結(jié)果:
{"status":500,"msg":"該郵箱已被注冊(cè)","data":null}代碼中,MultiValueMap是Map的一個(gè)子類(lèi),它的一個(gè)key可以存儲(chǔ)多個(gè)value,簡(jiǎn)單的看下這個(gè)接口:
| 1 | public interface MultiValueMap<K, V> extends Map<K, List<V>> {...} |
為什么用MultiValueMap?因?yàn)镠ttpEntity接受的request類(lèi)型是它。
| 1 2 | public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers){} //我這里只展示它的一個(gè)construct,從它可以看到我們傳入的map是請(qǐng)求體,headers是請(qǐng)求頭。 |
為什么用HttpEntity是因?yàn)閞estTemplate.postForEntity方法雖然表面上接收的request是@Nullable Object request類(lèi)型,但是你追蹤下去會(huì)發(fā)現(xiàn),這個(gè)request是用HttpEntity來(lái)解析。核心代碼如下:
| 1 2 3 4 5 6 7 | if (requestBody instanceof HttpEntity) { ????this.requestEntity = (HttpEntity<?>) requestBody; }else if (requestBody != null) { ????this.requestEntity = new HttpEntity<>(requestBody); }else { ????this.requestEntity = HttpEntity.EMPTY; } |
我曾嘗試用map來(lái)傳遞參數(shù),編譯不會(huì)報(bào)錯(cuò),但是執(zhí)行不了,是無(wú)效的url request請(qǐng)求(400 ERROR)。其實(shí)這樣的請(qǐng)求方式已經(jīng)滿(mǎn)足post請(qǐng)求了,cookie也是屬于header的一部分。可以按需求設(shè)置請(qǐng)求頭和請(qǐng)求體。其它方法與之類(lèi)似。
4.使用exchange指定調(diào)用方式
exchange()方法跟上面的getForObject()、getForEntity()、postForObject()、postForEntity()等方法不同之處在于它可以指定請(qǐng)求的HTTP類(lèi)型。
但是你會(huì)發(fā)現(xiàn)exchange的方法中似乎都有@Nullable HttpEntity?requestEntity這個(gè)參數(shù),這就意味著我們至少要用HttpEntity來(lái)傳遞這個(gè)請(qǐng)求體,之前說(shuō)過(guò)源碼所以建議就使用HttpEntity提高性能。
示例
????| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @Test ????public void rtExchangeTest() throws JSONException { ????????RestTemplate restTemplate = new RestTemplate(); ????????String url = "http://xxx.top/notice/list"; ????????HttpHeaders headers = new HttpHeaders(); ????????headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); ????????JSONObject jsonObj = new JSONObject(); ????????jsonObj.put("start",1); ????????jsonObj.put("page",5); ????????HttpEntity<String> entity = new HttpEntity<>(jsonObj.toString(), headers); ????????ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, ??????????????????????????????????????????HttpMethod.GET, entity, JSONObject.class); ????????System.out.println(exchange.getBody()); ????} |
這次可以看到,我使用了JSONObject對(duì)象傳入和返回。
當(dāng)然,HttpMethod方法還有很多,用法類(lèi)似。
5.excute()指定調(diào)用方式
excute()的用法與exchange()大同小異了,它同樣可以指定不同的HttpMethod,不同的是它返回的對(duì)象是響應(yīng)體所映射成的對(duì)象,而不是ResponseEntity。
需要強(qiáng)調(diào)的是,execute()方法是以上所有方法的底層調(diào)用。隨便看一個(gè):
????| 1 2 3 4 5 6 7 8 9 10 | @Override ????@Nullable ????public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables) ????????????throws RestClientException { ????????RequestCallback requestCallback = httpEntityCallback(request, responseType); ????????HttpMessageConverterExtractor<T> responseExtractor = ????????????????new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger); ????????return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables); |
總結(jié)
以上是生活随笔為你收集整理的转: Springboot — 用更优雅的方式发HTTP请求(RestTemplate详解)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 转:java网络编程-HTTP编程
- 下一篇: gradle idea java ssm