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
I did not see an example posted of how to actually do this with a custom interceptor, so here is one for reference sake:
public class MyXmlInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
HttpHeaders headers = response.getHeaders();
// you'd want to check if the value needs to be changed
if (headers.containsKey("Content-Type")) {
headers.remove("Content-Type");
}
headers.add("Content-Type", "application/xml");
return response;
}
Then, you would need to add the interceptor to your RestTemplate object:
RestTemplate t = new RestTemplate();
t.getInterceptors().add(new MyXmlInterceptor());
Can you change the content-type header before unmarshalling happens, by adding a custom interceptor http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/http/client/ClientHttpRequestInterceptor.html ?
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);