由于spring已经集成了http请求,底层还是基于httpclient封装的。同事要调用我的服务,采用HTTP请求调用,我推荐他使用restTemplate。但是他那边一直报错提示:ClassCastException: java.util.LinkedHashMap 。cannot be cast to。
他编写的代码如下:
//设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(BankConstant.ContentType, BankConstant.ContentTypeValue);
//将请求头和请求参数设置到HttpEntity中
HttpEntity<Object> httpEntity = new HttpEntity<>(object, httpHeaders);
log.info("调用outreach-api请求入参 request:{}, outreachApiBaseUrl:{}, url:{}", JSON.toJSONString(object),outreachApiBaseUrl, url);
Result result = restTemplate.postForObject(outreachApiBaseUrl + url, httpEntity, Result.class);
原来spring的restTemplate默认不识别的类型,都会转化为LinkedHashMap,这个时候restTemplate提供了exchange可以解决这个问题:
HttpEntity<Object> entity = new HttpEntity<>( dto);
ResponseEntity<Result<AccountDetailVO>> resultResponseEntity = restTemplate.exchange("https://test.qjdchina.com/unionPay/united/accountDetail", HttpMethod.POST,entity, new ParameterizedTypeReference<Result<AccountDetailVO>>() {});
System.out.println(resultResponseEntity);
AccountDetailVO accountDetailVO = resultResponseEntity.getBody().getData();
System.out.println(accountDetailVO)
还有一种简单的方法,通过字符串去接收字符串,然后通过json转化为对象:
String resp = restTemplate.postForObject("https://test.qjdchina.com/unionPay/united/accountDetail", entity, String.class);
Result<AccountDetailVO> result = JSON.parseObject(resp, new TypeReference<Result<AccountDetailVO>>() {});
System.out.println(result);
System.out.println(result.getData());