Spring RestTemplate 消息转换2种使用方式

拦截器

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;
}
RestTemplate t = new RestTemplate();
t.getInterceptors().add(new MyXmlInterceptor());

自定义

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);