Force Spring RestTemplate to use XmlConverter

后端 未结 3 682
野的像风
野的像风 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());
    

提交回复
热议问题