没有为响应类型找到合适的 HttpMessageConverter

2022-08-31 20:29:58

使用弹簧,使用此代码:

List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
for(HttpMessageConverter httpMessageConverter : messageConverters){
  System.out.println(httpMessageConverter);
}
ResponseEntity<ProductList> productList = restTemplate.getForEntity(productDataUrl,ProductList.class);

我得到

org.springframework.http.converter.ByteArrayHttpMessageConverter@34649ee4
org.springframework.http.converter.StringHttpMessageConverter@39fba59b
org.springframework.http.converter.ResourceHttpMessageConverter@383580da
org.springframework.http.converter.xml.SourceHttpMessageConverter@409e850a
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@673074aa
org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@1e3b79d3
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@52bb1b26

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.mycopmany.ProductList] and content type [text/html;charset=UTF-8]

pojo 的片段 :

@XmlRootElement(name="TheProductList")
public class ProductList {

@XmlElement(required = true, name = "date")
private LocalDate importDate;

答案 1

从 Spring 的角度来看,注册到 的实例都不能将内容转换为对象。感兴趣的方法是 。上述所有返回的实现,包括 。HttpMessageConverterRestTemplatetext/htmlProductListHttpMessageConverter#canRead(Class, MediaType)falseJaxb2RootElementHttpMessageConverter

由于 no 可以读取您的 HTTP 响应,因此处理将失败并出现异常。HttpMessageConverter

如果可以控制服务器响应,请对其进行修改以将 、 或与 之匹配的内容设置为 。Content-typeapplication/xmltext/xmlapplication/*+xml

如果您不控制服务器响应,则需要编写并注册自己的(可以扩展Spring类,请参阅及其子类),以便读取和转换。HttpMessageConverterAbstractXmlHttpMessageConvertertext/html


答案 2

您也可以简单地告诉您接受所有媒体类型:RestTemplate

@Bean
public RestTemplate restTemplate() {
   final RestTemplate restTemplate = new RestTemplate();

   List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
   MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
   converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
   messageConverters.add(converter);
   restTemplate.setMessageConverters(messageConverters);

   return restTemplate;
}

推荐