开发笔记:响应头是application/xml,响应体内容为json,导致springweb解析报错

服务端环境

依赖包版本
springCloudHoxton.SR6
springBoot2.3.0.RELEASE

调用百度ocr接口异常

调用接口 https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise 报如下异常:

org.springframework.web.client.RestClientException: Error while extracting response for type [class uca.common.baidubce.vo.RecogniseRespVo] and content type [application/xml;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character '{' (code 123) in prolog; expected '<'

原因

debug发现百度ocr接口返回数据如下:
在这里插入图片描述

返回内容表头Content-Type: application/xml;charset=UTF-8 ,但表体内容为json。

请求是使用spring提供RestTemplate类发出的,spring解析返回内容时把表体内容作为xml解析,导致解析报错。

解决

解决方法如下,改造RestTemplate:

原来的代码:

@Bean
BaiduBceOcrRequester baiduBceOcrRequester(RestTemplate restTemplate, AdminConfiguration configuration) {
	return new BaiduBceOcrRequester(restTemplate, configuration.getBaiduBce().getOcr());
}

修改后的代码:

@Bean
BaiduBceOcrRequester baiduBceOcrRequester(ObjectMapper objectMapper, AdminConfiguration configuration) {
    RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
    List<MediaType> supportedType = new ArrayList<>();
    supportedType.addAll(mappingJackson2HttpMessageConverter.getSupportedMediaTypes());
    mappingJackson2HttpMessageConverter.setSupportedMediaTypes(supportedType);
    restTemplate.getMessageConverters().add(0, mappingJackson2HttpMessageConverter);
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new LoggingRequestInterceptor());
    restTemplate.setInterceptors(interceptors);
    return new BaiduBceOcrRequester(restTemplate, configuration.getBaiduBce().getOcr());
}

关注公众号:java编程秀,获取更多Java最新资讯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

楚洛瞬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值