服务端环境
依赖包 | 版本 |
---|---|
springCloud | Hoxton.SR6 |
springBoot | 2.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最新资讯