Force Spring RestTemplate to use XmlConverter

后端 未结 3 679
野的像风
野的像风 2020-12-15 08:25

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

相关标签:
3条回答
  • 2020-12-15 08:28

    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());
    
    0 讨论(0)
  • 2020-12-15 08:47

    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 ?

    0 讨论(0)
  • 2020-12-15 08:53

    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);
    
    0 讨论(0)
提交回复
热议问题