RestTemplat中關于getForobject方法的使用
RestTemplat中getForobject方法使用
在接短信平臺的接口時,使用了RestTemplate的getForObject方法,自以為會自動拼接參數(shù),所以只傳了url和保存參數(shù)的map,但是多次提交失敗,以為是中間轉碼出錯
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
? ? ? ? return restTemplate.getForObject(url, responseType, uriVariables);
}經(jīng)過查看源碼,發(fā)現(xiàn)最后并沒有把參數(shù)拼接到url上,然后找了資料才發(fā)現(xiàn)了正確用法,尷尬~原來不是自動把map的key和value拼接到url上面,而是需要自己先指定好。
即:
http://localhost:8080/shortmessageservice.asmx/Send?sysName={sysName}&phoneNumbers={phoneNumbers}&content={content}&priority={priority}要用占位符指定到參數(shù)對應的key,和自定義的map一樣,使用getForObject方法即可成功把參數(shù)拼接上去。
//map的定義
? ? Map<String,String> request = new HashMap<>();
? ? request.put("sysName","username");
? ? request.put("phoneNumbers","13800138000");
? ? request.put("content","內(nèi)容");
? ? request.put("priority", "getforobject");RestTemplate關于getForObject()的正確用法
在使用RestTemplate的getForObject()方法時一直報錯,原來是因為使用map傳參需要固定RestTemplate訪問的url格式。
比如我想攜帶appId和appKey這兩個參數(shù),就得在url里面顯示聲明出來,特此記錄一下
解決
RestTemplate restTemplate = null;
InfoResponse response = null;
restTemplate = GenericObjectPoolUtils.borrowObject(RestTemplate.class);
Map<String, String> hashMap = new HashMap<>(5);
hashMap.put("appId", appId);
hashMap.put("appKey", appKey);
response = restTemplate.getForObject(
? ? ? ? "http://localhost:8083/api/getinfo?appId={appId}&appKey={appKey}"
? ? ? ? InfoResponse.class, hashMap
);總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解spring applicationContext.xml 配置文件
本篇文章主要介紹了詳解spring applicationContext.xml 配置文件 ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
Nacos服務發(fā)現(xiàn)并發(fā)啟動scheduleUpdate定時任務的流程分析
這篇文章主要介紹了Nacos服務發(fā)現(xiàn)并發(fā)啟動scheduleUpdate定時任務,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
java web開發(fā)之購物車功能實現(xiàn)示例代碼
這篇文章主要介紹了java web開發(fā)之購物車功能實現(xiàn)示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10

