/**
* 以传统form表单的方式提交参数(并不是以json格式提交)
*
* @param url 提交的rest url
* @param paramMap body参数
* @param responseType 返回类型
* @param <T>
* @return
*/
public <T> T postForFormObject(String url, Map<String, Object> paramMap, Class<T> responseType, Object... uriVariables) {
long astart = System.currentTimeMillis();
LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
T result = null;
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
map.add(entry.getKey(), String.valueOf(entry.getValue()));
logger.info("key: {} value:{}",entry.getKey(),String.valueOf(entry.getValue()));
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<LinkedMultiValueMap<String, String>> httpEntity = new HttpEntity<LinkedMultiValueMap<String, String>>(map, httpHeaders);
try {
if (null != uriVariables) {
result = restTemplate.postForObject(url, httpEntity, responseType,uriVariables);
}else{
result = restTemplate.postForObject(url, httpEntity, responseType);
}
}catch (Exception e){
logger.error("", e);
} finally {
long aend = System.currentTimeMillis();
logger.debug("url: {} invoke restful time consuming:{}", url, aend - astart);
log(url + "/" + (StringUtils.isEmpty(uriVariables) ? "" : JsonUtil.writeObjectValueAsString(uriVariables)), null, result);
}
return result;
}
有时候调用rest接口的时候,接口接收的参数并不是以json格式接收,而是以传统表单数据的格式接收,这时候他这contetentType就不是json,这时候需要通过封装一个HttpEntity再组装好相关参数提交httpEntity,参数的组装用的是LinkedMultiValueMap 貌似HttpEntity不接收value是object,所以String.valueOf将value值转成了String,这样就可以给rest接口传递表单的数据了