RestTemplat中关于getForobject方法的使用
作者:程序媛是个软妹子
这篇文章主要介绍了RestTemplat中关于getForobject方法的使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
RestTemplat中getForobject方法使用
在接短信平台的接口时,使用了RestTemplate的getForObject方法,自以为会自动拼接参数,所以只传了url和保存参数的map,但是多次提交失败,以为是中间转码出错
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
return restTemplate.getForObject(url, responseType, uriVariables);
}经过查看源码,发现最后并没有把参数拼接到url上,然后找了资料才发现了正确用法,尴尬~原来不是自动把map的key和value拼接到url上面,而是需要自己先指定好。
即:
http://localhost:8080/shortmessageservice.asmx/Send?sysName={sysName}&phoneNumbers={phoneNumbers}&content={content}&priority={priority}要用占位符指定到参数对应的key,和自定义的map一样,使用getForObject方法即可成功把参数拼接上去。
//map的定义
Map<String,String> request = new HashMap<>();
request.put("sysName","username");
request.put("phoneNumbers","13800138000");
request.put("content","内容");
request.put("priority", "getforobject");RestTemplate关于getForObject()的正确用法
在使用RestTemplate的getForObject()方法时一直报错,原来是因为使用map传参需要固定RestTemplate访问的url格式。
比如我想携带appId和appKey这两个参数,就得在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
);总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
