RestTemplate實(shí)現(xiàn)發(fā)送帶headers的GET請(qǐng)求
RestTemplate 發(fā)送帶headers的GET請(qǐng)求
需求:發(fā)送自定義header的GET請(qǐng)求,header中需要插入一個(gè)簽名。
發(fā)送自定義header的POST請(qǐng)求
之前寫(xiě)過(guò)一個(gè)類(lèi)似的請(qǐng)求,但是是POST的。這個(gè)也摸了一段時(shí)間,自己看參數(shù)整了出來(lái)。代碼如下:
// header填充
LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.put("Content-Type", Collections.singletonList("application/json;charset=UTF-8"));
headers.put("signature", Collections.singletonList(makeSignature(form.getNewMobile())));
// body填充
JSONObject json = new JSONObject();
json.put("oldMobile", mobile);
json.put("newMobile", form.getNewMobile());
HttpEntity<String> request = new HttpEntity<String>(json.toString(), headers);
// 一個(gè)單例的restTemplate
RestTemplate restTemplate = HttpInvoker.getRestTemplate();
// 發(fā)送請(qǐng)求
ResponseEntity<String> response = restTemplate.postForEntity(whiteListURL, request, String.class);
很簡(jiǎn)單的想著,只需要把上面的postForEntity()改成get的就行,但不是這樣的。

發(fā)送自定義header的GET請(qǐng)求
Update: 2019/12/11
從鏈接學(xué)到了一種比較友好的寫(xiě)法:
private static void getEmployees(){
final String uri = "http://localhost:8080/springrestexample/employees";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
System.out.println(result);
}
粗略看了看postForEntity()和getForEntity()這兩個(gè)方法的實(shí)現(xiàn),都是準(zhǔn)備參數(shù),然后調(diào)用execute()方法,如下:
// POST
@Override
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request,
Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = httpEntityCallback(request, responseType);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
return nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables));
}
// GET
@Override
@Nullable
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
}
區(qū)別就在于RequestCallback實(shí)例化的時(shí)候,傳的參數(shù)不一樣。POST的時(shí)候,是將header做為參數(shù)傳給了RequestCallback。再然后就是execute()中的GET和POST參數(shù)不一樣。到這個(gè)時(shí)候,發(fā)送自定義header的GET請(qǐng)求,已經(jīng)很明顯了。
實(shí)例化的函數(shù),都是public的。
如果不是public的,或者說(shuō)我們不能直接訪(fǎng)問(wèn)到,還可以考慮通過(guò)反射的方式去調(diào)用相關(guān)的方法,但這里不需要用反射了。
結(jié)果
// header填充
LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.put("Content-Type", Collections.singletonList("application/json;charset=UTF-8"));
headers.put("signature", Collections.singletonList(makeSignature(mobile)));
// 獲取單例RestTemplate
RestTemplate restTemplate = HttpInvoker.getRestTemplate();
HttpEntity request = new HttpEntity(headers);
// 構(gòu)造execute()執(zhí)行所需要的參數(shù)。
RequestCallback requestCallback = restTemplate.httpEntityCallback(request, JSONObject.class);
ResponseExtractor<ResponseEntity<JSONObject>> responseExtractor = restTemplate.responseEntityExtractor(JSONObject.class);
// 執(zhí)行execute(),發(fā)送請(qǐng)求
ResponseEntity<JSONObject> response = restTemplate.execute(apiAddress + "/xxx/whitelist/check?phone=" + mobile, HttpMethod.GET, requestCallback, responseExtractor);
雖然很簡(jiǎn)單,但是看似不可能,自己卻做到了、完成了,就很有成就感。
RestTemplate優(yōu)雅的發(fā)送Get請(qǐng)求
在我們的項(xiàng)目中,如果借助RestTemplate發(fā)送帶參數(shù)的Get請(qǐng)求,我們可以通過(guò)拼接字符串的方式將url拼接出來(lái),比如下面這種方式:
String url = "http://127.0.0.1:8080/rest/get?name="+ name +"&id=" + id; ResponseEntity<RestVO> forEntity = restTemplate.getForEntity(url, RestVO.class);
然而這種方式不太優(yōu)雅,我們還可以通過(guò)以下幾種方式發(fā)送Get請(qǐng)求
方式1:使用占位符
String url = "http://127.0.0.1:8080/rest/path/{name}/{id}";
Map<String, Object> params = new HashMap<>();
params.put("name", "這是name");
params.put("id", 1L);
ResponseEntity<RestVO> forEntity = restTemplate.getForEntity(url, RestVO.class, params);
Map的key要和url中的占位符一致
方式2:使用LinkedMultiValueMap和UriComponentsBuilder
String url = "http://127.0.0.1:8080/rest/get";
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("name", "這是name");
params.add("id", "1");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = builder.queryParams(params).build().encode().toUri();
ResponseEntity<RestVO> forEntity = restTemplate.getForEntity(uri, RestVO.class);
return forEntity.getBody();
方式2看起來(lái)是最優(yōu)雅的,將參數(shù)的設(shè)置和url分離。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Netty搭建WebSocket服務(wù)器實(shí)戰(zhàn)教程
這篇文章主要介紹了Netty搭建WebSocket服務(wù)器實(shí)戰(zhàn),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-03-03
實(shí)例解析Java設(shè)計(jì)模式編程中的適配器模式使用
本篇文章主要通過(guò)實(shí)例對(duì)適配器模式進(jìn)行了詳解,需要的朋友可以參考下2017-04-04
spring boot項(xiàng)目fat jar瘦身的實(shí)現(xiàn)
這篇文章主要介紹了spring boot項(xiàng)目fat jar瘦身的實(shí)現(xiàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
springboot vue完成發(fā)送接口請(qǐng)求顯示響應(yīng)頭信息
這篇文章主要為大家介紹了springboot+vue完成發(fā)送接口請(qǐng)求顯示響應(yīng)頭信息,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
scala+redis實(shí)現(xiàn)分布式鎖的示例代碼
這篇文章主要介紹了scala+redis實(shí)現(xiàn)分布式鎖的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
java操作mongodb之多表聯(lián)查的實(shí)現(xiàn)($lookup)
這篇文章主要介紹了java操作mongodb之多表聯(lián)查的實(shí)現(xiàn)($lookup),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Java實(shí)現(xiàn)驗(yàn)證碼的產(chǎn)生和驗(yàn)證
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)驗(yàn)證碼的產(chǎn)生和驗(yàn)證,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2012-01-01

