简体   繁体   English

使用Spring时获取HttpMessageNotReadableException异常-RestTemplate

[英]Get HttpMessageNotReadableException Exception when using Spring - RestTemplate

I'm using springframework -RestTemplate, in order to make get request , and convert the xml response to java object. 我正在使用springframework -RestTemplate,以便进行get request,并将xml响应转换为java对象。 After the operation : RestTemplate.exchange, I got the following exception: 操作:RestTemplate.exchange之后,出现以下异常:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not instantiate value of type [simple type, class Order] from 

The response from the client in XML, and I added it to the headers: 来自客户端的XML响应,我将其添加到标题中:

headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));

So why it's trying to parse the response as JSON? 那么,为什么要尝试将响应解析为JSON? and how can I resolve it? 以及如何解决?

Thanks!! 谢谢!!

The most common cause is you are getting some XML which does not conform to the deserialization rules defined in your model (or maybe it is malformed XML). 最常见的原因是您得到的XML不符合模型中定义的反序列化规则(或者它是格式错误的XML)。

Other possible cause is your RestTemplate missing a message converter capable of dealing with XML conversion. 其他可能的原因是RestTemplate缺少能够处理XML转换的消息转换器。 By default, Spring Boot configures a Jaxb2RootElementHttpMessageConverter , but only if you have JAXB2 in your classpath, so you should check this dependency is available to your project. 默认情况下,Spring Boot配置一个Jaxb2RootElementHttpMessageConverter ,但是仅当您在类路径中有JAXB2时,因此您应该检查此依赖项是否可用于您的项目。

You can print which message converters are registered in your RestTemplate , and which media types they accept, with the following code: 您可以使用以下代码打印在RestTemplate中注册了哪些消息转换器,以及它们接受哪些媒体类型:

for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
    System.out.println("Converter: " + converter.getClass().getSimpleName() + ", supports: "
                + converter.getSupportedMediaTypes().toString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM