Spring的RestTemplata使用的具體方法
基本概念
Spring RestTemplate 是 Spring 提供的用于訪問 Rest 服務(wù)的客戶端,RestTemplate 提供了多種便捷訪問遠(yuǎn)程Http服務(wù)的方法,能夠大大提高客戶端的編寫效率,所以很多客戶端比如 Android或者第三方服務(wù)商都是使用 RestTemplate 請求 restful 服務(wù)。
spring-web的RestTemplata是對java底層http的封裝,使用RestTemplata用戶可以不再關(guān)注底層的連接建立,并且RestTemplata不僅支持Rest規(guī)范,還可以定義返回值對象類型。
在使用中可以直接new一個RestTemplate對象,在我們創(chuàng)建的RestTemplate對象中會有一些返回消息的消息轉(zhuǎn)換器,可以根據(jù)返回數(shù)據(jù)的 MediaType 尋找對應(yīng)的轉(zhuǎn)換器并進(jìn)行 MediaType 轉(zhuǎn)換。自己也可以創(chuàng)建消息轉(zhuǎn)換器,創(chuàng)建一個類繼承AbstractGenericHttpMessageConverter<T>類或者實(shí)現(xiàn)HttpMessageConverter<T>接口,需要注意的是canRead方法和canWrite方法最好自己做判斷,在writeInternal或write方法中將參數(shù)寫入到流,在readInternal或read方法中將返回結(jié)果從流的body中獲取并進(jìn)行類型映射。
RestTemplate對象在底層通過使用java.net包下的實(shí)現(xiàn)創(chuàng)建HTTP 請求,可以通過使用ClientHttpRequestFactory指定不同的HTTP請求方式。
ClientHttpRequestFactory接口主要提供了兩種實(shí)現(xiàn)方式:
- 一種是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)創(chuàng)建底層的Http請求連接。
- 一種方式是使用HttpComponentsClientHttpRequestFactory方式,底層使用HttpClient訪問遠(yuǎn)程的Http服務(wù),使用HttpClient可以配置連接池和證書等信息。
RestTemplate默認(rèn)是使用SimpleClientHttpRequestFactory,內(nèi)部是調(diào)用jdk的HttpConnection,默認(rèn)超時為-1,我們可以自己定義超時時間
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); //設(shè)置連接超時,單位毫秒 factory.setConnectTimeout(5000); //設(shè)置讀取超時,單位毫秒 factory.setReadTimeout(10000); RestTemplate restTemplate = new RestTemplate(factory);
使用GET請求:
String url = "http://localhost:80/mandy/login.json?account=123456&password=123456"; Result res = restTemplate.getForObject(url, Result.class);
RestTemplate源碼:
@Override
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor, urlVariables);
}
使用get請求直接將參數(shù)拼接到地址上最好,不知道什么原因如果使用第三個參數(shù),即便是MultiValueMap類型也不行(網(wǎng)上有人說用MultiValueMap類型可以,我試了不行)
使用POST請求:
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", "測試");
map.put("account", "qwer");
map.put("password", "qwer");
ObjectMapper mapper = new ObjectMapper();
String jsonStr = null;
try {
jsonStr = mapper.writeValueAsString(map);
} catch (Exception e) {
e.printStackTrace();
}
//創(chuàng)建HTTP頭部實(shí)體,填充頭部信息,比如數(shù)據(jù)格式
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
//創(chuàng)建HTTP實(shí)體,可以直接利用構(gòu)造方法將請求體和請求頭放進(jìn)去
HttpEntity<String> httpEntity = new HttpEntity<String>(jsonStr2, httpHeaders);
String url = "http://localhost:80/mandy/user_enable.json";
//調(diào)用方法進(jìn)行請求
Result res2 = restTemplate.postForObject(url, httpEntity, Result.class);
RestTemplate源碼:
@Override
public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
}
使用PUT請求:
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("user_id", "1");
map.put("enable", 0);
ObjectMapper mapper = new ObjectMapper();
String jsonStr = null;
try {
jsonStr = mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//創(chuàng)建HTTP頭部實(shí)體,填充頭部信息,比如數(shù)據(jù)格式
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
//創(chuàng)建HTTP實(shí)體,可以直接利用構(gòu)造方法將請求體和請求頭放進(jìn)去
HttpEntity<String> httpEntity = new HttpEntity<String>(jsonStr, httpHeaders);
String url = "http://localhost:80/mandy/user_enable.json";
restTemplate.put(url , httpEntity);
RestTemplate源碼:
@Override
public void put(String url, Object request, Object... urlVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request);
execute(url, HttpMethod.PUT, requestCallback, null, urlVariables);
}
這個方法有個小的缺點(diǎn)就是沒有請求結(jié)果的返回值,如果需要用到返回值,就不能用這個方法。
如果要使用delete類型的請求,RestTemplate的put方法的參數(shù)列中只有下面幾種
@Override
public void delete(String url, Object... urlVariables) throws RestClientException {
execute(url, HttpMethod.DELETE, null, null, urlVariables);
}
@Override
public void delete(String url, Map<String, ?> urlVariables) throws RestClientException {
execute(url, HttpMethod.DELETE, null, null, urlVariables);
}
@Override
public void delete(URI url) throws RestClientException {
execute(url, HttpMethod.DELETE, null, null);
}
這些方法并沒有給我們參數(shù)讓我們放請求體內(nèi)容,所以如果要直接使用RestTemplate提供的Delete方法,接口必須使用restful風(fēng)格,將參數(shù)放在地址中,通過@PathVariable(value="")注解將參數(shù)獲取到。
重點(diǎn): 其實(shí)我們可以直接使用RestTemplate的 exchange 方法,如下
@Override
public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, method, requestCallback, responseExtractor, uriVariables);
}
這里只列舉了一個方法,其他的可以看源碼,這個方法可以進(jìn)行所有類型的請求。
在這個方法中,method參數(shù)可以通過HTTPMethod枚舉來進(jìn)行獲取,requestEntity參數(shù)是自己封裝的HttpEntity實(shí)體,包含請求體和請求頭,responseType參數(shù)是返回結(jié)果的映射類,uriVariables這個參數(shù)給我的印象就是雞肋(個人看法),獲取請求返回接口可以通過方法返回值的getBody()方法獲取。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Java數(shù)組的一維和二維講解和內(nèi)存顯示圖
這篇文章主要介紹了Java數(shù)組的一維和二維講解和內(nèi)存顯示圖,數(shù)組就相當(dāng)于一個容器,存放相同類型數(shù)據(jù)的容器。而數(shù)組的本質(zhì)上就是讓我們能 "批量" 創(chuàng)建相同類型的變量,需要的朋友可以參考下2023-05-05
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(27)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望可以幫到你2021-07-07
Java并發(fā)編程包中atomic的實(shí)現(xiàn)原理示例詳解
這篇文章主要給大家介紹了關(guān)于Java并發(fā)編程包中atomic的實(shí)現(xiàn)原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09

