Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

java - Force Spring RestTemplate to use XmlConverter

We are integrating with a third party that is sending xml with the content-type header as text/html. We were planning on using Spring's RestTemplate to map it to classes we've generated from xsds, but the RestTemplate fails to find an appropriate converter to use for the content. The third party refuses to fix the content-type because it might break other partners' integration.

Is there a way with Spring's RestTemplate to force it to use a specific converter? We are basically just doing the following:

RestTemplate restTemplate = new RestTemplate();
XmlClass xmlClass = restTemplate.getForObject("http://example.com/", XmlClass.class);

And get the following exception:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [XmlClass] and content type [text/html;charset=ISO-8859-1] at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:84)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The solution we implemented was to add a Jaxb2RootElementHttpMessageConverter with MediaType.TEXT_HTML to the RestTemplate HttpMessageConverters. It's not ideal since it creates a redundant jaxb message converter but it works.

RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
Jaxb2RootElementHttpMessageConverter jaxbMessageConverter = new Jaxb2RootElementHttpMessageConverter();
List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.TEXT_HTML);
jaxbMessageConverter.setSupportedMediaTypes(mediaTypes);
messageConverters.add(jaxbMessageConverter);
restTemplate.setMessageConverters(messageConverters);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...