java.util.LinkedHashMap cannot be cast to org.springframework.util.MultiValueMap
RestTemplate.exchange()
Map不能定义为以下两种类型(url使用占位符进行参数传递时除外)
Map<String, Object> paramMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
经测试这两种Map里面的参数都不能被所请求的接口收到,把Map类型换成LinkedMultiValueMap后,参数成功传递到所请求的接口。
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
当 RestTemplate.exchange() 的 requestEntity 的类型为 LinkedHashMap 的时候(这个情况在环境1接口请求转发到环境2做接口请求时出现)
MultiValueMap<String, String> formDataMap = new LinkedMultiValueMap<String, String>();
String bodyStr = requestEntity.getBody().toString(); // requestEntity.getBody()为LinkedHashMap数据类型
JSONObject jsonObject = JSONObject.fromObject(bodyStr);
Map<String, String> bodyMap = JSONObject.fromObject(jsonObject);
for (Map.Entry entry : bodyMap.entrySet()) {
String mapKey = entry.getKey().toString();
String mapValue = entry.getValue().toString(); // LinkedHashMap数据类型的value值最外层有中括号[]
formDataMap.set(mapKey, mapValue.substring(1, mapValue.length() - 1)); //用正则表达式去掉LinkedHashMap数据类型的value值最外层有中括号[],set()方法在value最外层添加中括号[]
}
HttpEntity<?> reqEntity = new HttpEntity(formDataMap, requestEntity.getHeaders());
ResponseEntity<T> responseEntity = null;
responseEntity = restTemplate.exchange(url, method, reqEntity, responseType, uriVariables);
本文主要探讨了在使用Java的RestTemplate进行接口调用时遇到的参数传递问题。当尝试将Map类型作为参数传递时,无论是HashMap还是LinkedHashMap,参数都无法正确到达目标接口。解决方法是使用MultiValueMap,特别是LinkedMultiValueMap,通过这种方式可以成功传递参数。在特定情况下,如接口请求转发,可能会遇到LinkedHashMap作为请求主体的情况,此时需要将LinkedHashMap的数据转换为MultiValueMap形式才能正确处理。
2695

被折叠的 条评论
为什么被折叠?



