Reputation: 199
Spring boot application where I have a generic class ApiCaller to call different urls. I am using RestTemplate to make the calls. The detail to make the call comes from our internal db.
switch (serviceRequest.getMethod()) {
case "POST":
response = this.restTemplate.postForEntity(url,serviceRequestBody, Map.class).getBody();
break;
case "GET":
response = this.restTemplate.getForEntity(url,serviceRequestBody, Map.class).getBody();
break;
default:
break;
}
As can be seen, I am sending the responseType as Map.class, which converts the response from the api to a map. It works fine the apis which returns json response. However, it does not work for resources which returns xml response. It gives below exception:
no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [application/xml]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:110) ~[spring-web-4.3.18.RELEASE.jar!/:4.3.18.RELEASE]
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:932) ~[spring-web-4.3.18.RELEASE.jar!/:4.3.18.RELEASE]
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:916) ~[spring-web-4.3.18.RELEASE.jar!/:4.3.18.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:663) ~[spring-web-4.3.18.RELEASE.jar!/:4.3.18.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621) ~[spring-web-4.3.18.RELEASE.jar!/:4.3.18.RELEASE]
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:415) ~[spring-web-4.3.18.RELEASE.jar!/:4.3.18.RELEASE]
I went through few similar problems and found that Custom messageConverter will solve this. Is there any built in HttpMessageConverter which can handle this?
Upvotes: 3
Views: 1702
Reputation: 40058
Add HttpMessageConverter
to RestTemplate
object to convert any type of response
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
//converter to process any kind of response,
converter.setSupportedMediaTypes(Arrays.asList({MediaType.ALL}));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
Upvotes: 3