请求三方接口时,对方返回的响应数据是text/html类型 怎么处理
原来的调用方式 默认只处理text/json类型的数据
public static JSONObject post(String url, HttpHeaders headers, Map body) {
RestTemplate restTemplate = new RestTemplate(factory);
HttpEntity entity = new HttpEntity(JSON.toJSONString(body), headers);
try {
log.info("地址:" + url);
JSONObject response = restTemplate.postForObject(url, entity, JSONObject.class);
log.info("请求发送成功");
return response;
} catch (Exception e) {
log.error("请求失败", e);
throw e;
}
}
原来的处理方式把接口的响应转为Json类型,但对方的响应是text/html类型,报错如下
第一次尝试把调用接口返回的数据先从String接收再进一步处理,奈何接收还是出现异常。
同接口方沟通 对方不理解什么是text/json 或者 text/html 处理起来较为麻烦(ps:或许也是我理解的有问题)
第二次尝试直接处理text/html类型数据
因为工具类是直接封装了restTemplate的调用,故从restTemplate入手
声明restTemplate-->createRestTemplate 能够处理text/html的数据
private static final RestTemplate restTemplate = createRestTemplate();
createRestTemplate的代码如下:
private static RestTemplate createRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
fastJsonHttpMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
restTemplate.getMessageConverters().add(0, fastJsonHttpMessageConverter);
restTemplate.getMessageConverters().add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
其中的FastJsonHttpMessageConverter说明:
按照createRestTemplate声明的restTemplate的进行调用 接收的返回数据仍以String的方式接收 再转为Json处理
public static JSONObject postForIcp(String url, Map body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity(JSON.toJSONString(body), headers);
try {
ResponseEntity response = restTemplate.postForEntity(url, entity, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
log.info("响应: " + responseBody);
return JSON.parseObject(responseBody);
} else {
log.error("请求失败,状态码: " + response.getStatusCodeValue());
throw new RuntimeException("请求失败,状态码: " + response.getStatusCodeValue());
}
} catch (Exception e) {
log.error("请求失败", e);
throw e;
}
}
数据成功接收并处理。
参与评论
手机查看
返回顶部