我正在使用 springframework -RestTemplate, 为了发出 get 请求,并将 xml 响应转换为 java 对象。 运行后:RestTemplate.exchange, 我遇到以下异常:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not instantiate value of type [simple type, class Order] from
来自 XML 格式的客户端响应,我将其添加到 header 中:
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
那么为什么它尝试将响应解析为 JSON 呢? 我该如何解决这个问题?
谢谢!!
最佳答案
最常见的原因是您获得的一些 XML 不符合模型中定义的反序列化规则(或者可能是格式错误的 XML)。
其他可能的原因是您的 RestTemplate
缺少能够处理 XML 转换的消息转换器。默认情况下,Spring Boot 会配置 Jaxb2RootElementHttpMessageConverter
,但前提是您的类路径中有 JAXB2,因此您应该检查此依赖项是否可用于您的项目。
您可以使用以下代码打印在 RestTemplate
中注册了哪些消息转换器以及它们接受哪些媒体类型:
for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
System.out.println("Converter: " + converter.getClass().getSimpleName() + ", supports: "
+ converter.getSupportedMediaTypes().toString());
}
关于java - 使用 Spring 时获取 HttpMessageNotReadableException 异常 - RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42293504/