RestTemplate是Spring提供的用於訪問Rest服務的客戶端,RestTemplate提供了多種便捷訪問遠程Http服務的方法,可以大大提升客戶端的編寫效率。html
我以前的HTTP開發是用apache的HttpClient開發,代碼複雜,還得操心資源回收等。代碼很複雜,冗餘代碼多,稍微截個圖,這是我封裝好的一個post請求工具:java
本教程將帶領你們實現Spring生態內RestTemplate的Get請求和Post請求還有exchange指定請求類型的實踐和RestTemplate核心方法源碼的分析,看完你就會用優雅的方式來發HTTP請求。nginx
是Spring用於同步client端的核心類,簡化了與http服務的通訊,並知足RestFul原則,程序代碼能夠給它提供URL,並提取結果。默認狀況下,RestTemplate默認依賴jdk的HTTP鏈接工具。固然你也能夠 經過setRequestFactory屬性切換到不一樣的HTTP源,好比Apache HttpComponents、Netty和OkHttp。spring
RestTemplate能大幅簡化了提交表單數據的難度,而且附帶了自動轉換JSON數據的功能,但只有理解了HttpEntity的組成結構(header與body),且理解了與uriVariables之間的差別,才能真正掌握其用法。這一點在Post請求更加突出,下面會介紹到。apache
該類的入口主要是根據HTTP的六個方法制定:json
此外,exchange和excute能夠通用上述方法。cookie
在內部,RestTemplate默認使用HttpMessageConverter實例將HTTP消息轉換成POJO或者從POJO轉換成HTTP消息。默認狀況下會註冊主mime類型的轉換器,但也能夠經過setMessageConverters註冊其餘的轉換器。ide
其實這點在使用的時候是察覺不到的,不少方法有一個responseType 參數,它讓你傳入一個響應體所映射成的對象,而後底層用HttpMessageConverter將其作映射工具
1
2
|
HttpMessageConverterExtractor<T> responseExtractor =
new
HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger);
|
HttpMessageConverter.java源碼:post
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public
interface
HttpMessageConverter<T> {
//指示此轉換器是否能夠讀取給定的類。
boolean
canRead(Class<?> clazz,
@Nullable
MediaType mediaType);
//指示此轉換器是否能夠寫給定的類。
boolean
canWrite(Class<?> clazz,
@Nullable
MediaType mediaType);
//返回List<MediaType>
List<MediaType> getSupportedMediaTypes();
//讀取一個inputMessage
T read(Class<?
extends
T> clazz, HttpInputMessage inputMessage)
throws
IOException, HttpMessageNotReadableException;
//往output message寫一個Object
void
write(T t,
@Nullable
MediaType contentType, HttpOutputMessage outputMessage)
throws
IOException, HttpMessageNotWritableException;
}
|
在內部,RestTemplate默認使用SimpleClientHttpRequestFactory和DefaultResponseErrorHandler來分別處理HTTP的建立和錯誤,但也能夠經過setRequestFactory和setErrorHandler來覆蓋。
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()其實比getForEntity()多包含了將HTTP轉成POJO的功能,可是getForObject沒有處理response的能力。由於它拿到手的就是成型的pojo。省略了不少response的信息。
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請求
1
2
3
4
5
6
7
8
9
10
|
/**
* 不帶參的get請求
*/
@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);
}
|
控制檯打印:
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 帶參數的get請求1
Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}"
, Notice.class,1,5);
明眼人一眼能看出是用了佔位符{1}。
示例:2.1.4 帶參數的get請求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裝載參數,不過它默認解析的是PathVariable的url形式。
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對象,若是須要轉換成pojo,還須要json工具類的引入,這個按我的喜愛用。不會解析json的能夠百度FastJson或者Jackson等工具類。而後咱們就研究一下ResponseEntity下面有啥方法。
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> {
//設置正文的長度,以字節爲單位,由Content-Length標頭
BodyBuilder contentLength(
long
contentLength);
//設置body的MediaType 類型
BodyBuilder contentType(MediaType contentType);
//設置響應實體的主體並返回它。
<T> ResponseEntity<T> body(
@Nullable
T body);
}
|
能夠看出來,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(
"我在這裏添加一句話"
);
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
]}>
|
固然,還有getHeaders()等方法沒有舉例。
一樣的,post請求也有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 {}
|
我用一個驗證郵箱的接口來測試。
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());
}
|
執行結果:
{"status":500,"msg":"該郵箱已被註冊","data":null}
代碼中,MultiValueMap是Map的一個子類,它的一個key能夠存儲多個value,簡單的看下這個接口:
1
|
public
interface
MultiValueMap<K, V>
extends
Map<K, List<V>> {...}
|
爲何用MultiValueMap?由於HttpEntity接受的request類型是它。
1
2
|
public
HttpEntity(
@Nullable
T body,
@Nullable
MultiValueMap<String, String> headers){}
//我這裏只展現它的一個construct,從它能夠看到咱們傳入的map是請求體,headers是請求頭。
|
爲何用HttpEntity是由於restTemplate.postForEntity方法雖然表面上接收的request是@Nullable Object request類型,可是你追蹤下去會發現,這個request是用HttpEntity來解析。核心代碼以下:
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來傳遞參數,編譯不會報錯,可是執行不了,是無效的url request請求(400 ERROR)。其實這樣的請求方式已經知足post請求了,cookie也是屬於header的一部分。能夠按需求設置請求頭和請求體。其它方法與之相似。
exchange()方法跟上面的getForObject()、getForEntity()、postForObject()、postForEntity()等方法不一樣之處在於它能夠指定請求的HTTP類型。
可是你會發現exchange的方法中彷佛都有@Nullable HttpEntity requestEntity這個參數,這就意味着咱們至少要用HttpEntity來傳遞這個請求體,以前說過源碼因此建議就使用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對象傳入和返回。
固然,HttpMethod方法還有不少,用法相似。
excute()的用法與exchange()大同小異了,它一樣能夠指定不一樣的HttpMethod,不一樣的是它返回的對象是響應體所映射成的對象,而不是ResponseEntity。
須要強調的是,execute()方法是以上全部方法的底層調用。隨便看一個:
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);
}
|