调用第三方服务接口使用RestTemplate方式,返回结果被转换为LinkedHashMap结构
服务方返回的对象结构:
public class SearchGroupBaseInfoResponse{
private List<SearchGroupBaseInfo> searchGroupBaseInfoList;
private int totalNum;
private int totalPage;
}
客户端调用方式:
ResponseEntity<ResponseObject> responseJson=null;
try{
entity = restTemplate.exchange(getGroupInfosUrl, HttpMethod.POST, httpEntity, ResponseObject.class);
}catch (Exception e){
log.error("当前时间【{}】调用UIMC获取团体用户信息服务异常,请求url={},异常信息:{}", DateUtil.getDateByDefaultPattern(new Date()), getGroupInfosUrl, e.getMessage(), e);
throw new BusinessException(CacheHelper.getRedisErrorMessageByKey(ActivityErrorCodeConstants.ProcessErrorCode.CALL_UIMC_GROUPINFO_ERR));
}
if(responseJson.getStatusCodeValue() != HTTP_RESPONSE_CODE||null==responseJson.getBody()){
log.info("调用UIMC获取团体用户信息,返回数据异常,状态码:【{}】,body:【{}】",responseJson.getStatusCodeValue(),responseJson.getBody());
throw new BusinessException(CacheHelper.getRedisErrorMessageByKey(ActivityErrorCodeConstants.ProcessErrorCode.CALL_UIMC_GET_GROUPINFO_ERR));
}
Object data=entity.getbody().getData();
单步调试的结果如下图:

原因:
因为RPC远程调用在底层还是使用HttpClient,所以在传递参数时,需要有个顺序,当传递map的时候map里面的值也要有顺序,不然服务层在接收的时候也会出问题,然而与Map对应有顺序的数据结构就是LinkedHashMap;spring有一个类叫ModelMap,继承了LinkedHashMap,所以一个接口返回的结果就可以直接用ModelMap来接收,ModelMap是没有范型的,不管返回的结果是什么类型的map,多么复杂的map,都可以用ModelMap来接收返回结果。
对于上述问题的解决方案:
使用ParameterizedTypeReference设置HttpRequestExecutingMessageHandler的setExpectedResponseType
代码如下:
ResponseEntity<ResponseObject<SearchGroupBaseInfoResponse>> entity=null;
//使用这种方式转换restTemplate接收返回LinkedHashMap类型的对象
ParameterizedTypeReference<ResponseObject<SearchGroupBaseInfoResponse>> typeRef= new ParameterizedTypeReference<ResponseObject<SearchGroupBaseInfoResponse>>() {};
try{
entity = restTemplate.exchange(getGroupInfosUrl, HttpMethod.POST, httpEntity, typeRef);
// responseJson= restTemplate.exchange(getGroupInfosUrl, HttpMethod.POST, httpEntity, JSONObject.class);
}catch (Exception e){
log.error("当前时间【{}】调用UIMC获取团体用户信息服务异常,请求url={},异常信息:{}", DateUtil.getDateByDefaultPattern(new Date()), getGroupInfosUrl, e.getMessage(), e);
throw new BusinessException(CacheHelper.getRedisErrorMessageByKey(ActivityErrorCodeConstants.ProcessErrorCode.CALL_UIMC_GROUPINFO_ERR));
}
if(responseJson.getStatusCodeValue() != HTTP_RESPONSE_CODE||null==responseJson.getBody()){
log.info("调用UIMC获取团体用户信息,返回数据异常,状态码:【{}】,body:【{}】",
responseJson.getStatusCodeValue(),responseJson.getBody());
throw new BusinessException(CacheHelper.getRedisErrorMessageByKey(ActivityErrorCodeConstants.ProcessErrorCode.CALL_UIMC_GET_GROUPINFO_ERR));
}
ResponseObject<SearchGroupBaseInfoResponse> body = entity.getBody();
SearchGroupBaseInfoResponse data1 = body.getData();
单步调试结果:

159

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



