Home  >  Forum  >  Spring
Post New Query

Could not extract response: no suitable HttpMessageConverter found for response type and content type



Asked on April 21, 2020
I am creating Spring REST client application using RestTemplate. When I try to consume XML response, it throws error. My client code is

URI uri = new URI("http://localhost:8080/book");
HttpHeaders headers = new HttpHeaders();
RequestEntity<List<Book>> reqEntity = new RequestEntity<>(headers, HttpMethod.GET, uri);
ParameterizedTypeReference<List<Book>> typeRef = new ParameterizedTypeReference<List<Book>>() {};

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Book>> resEntity = restTemplate.exchange(reqEntity, typeRef);

System.out.println(resEntity.getStatusCodeValue());
for (Book b : resEntity.getBody()) {
System.out.println(b);
}

Find the error.

Exception in thread "main" org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [] and content type [application/xml]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:123)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:998)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:981)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:741)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:651)

Any quick suggestion to solve the error?



Replied on April 21, 2020
You are missing to add MessageConverter to RestTemplate. As you are consuming XML, you can use
MappingJackson2XmlHttpMessageConverter.

URI uri = new URI("http://localhost:8080/book");

HttpHeaders headers = new HttpHeaders();
RequestEntity<List<Book>> reqEntity = new RequestEntity<>(headers, HttpMethod.GET, uri);
ParameterizedTypeReference<List<Book>> typeRef = new ParameterizedTypeReference<List<Book>>() {};

List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_XML));
messageConverters.add(converter);


RestTemplate restTemplate = new RestTemplate();       
restTemplate.setMessageConverters(messageConverters);
ResponseEntity<List<Book>> resEntity = restTemplate.exchange(reqEntity, typeRef);

System.out.println(resEntity.getStatusCodeValue());
for (Book b : resEntity.getBody()) {
    System.out.println(b);
}


You need to resolve jackson-dataformat-xml dependency.
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
  <version>2.10.3</version>
</dependency>



Replied on April 21, 2020
Thanks. It solved the problem.

Write Answer








©2020 concretepage.com | Privacy Policy | Contact Us