Skip to content

Spring RestTemplate message converter priority when posting

What is the most convenient way to influence the priority of the message converters Spring applies when POSTing with RestTemplate?

Use case: I want to ensure a given entity is POSTed as JSON rather than e.g. XML when I do restTemplate.postForEntity(url, entity, Void.class).


By default the entity is converted to XML because the MappingJackson2XmlHttpMessageConverter takes precedence over the MappingJackson2HttpMessageConverter. The default list of converters for my app appears to be (Spring scans the classpath to see what’s available): enter image description here

Option 1

You can configure the message converters explicitly for a given RestTemplate instance like so restTemplate.setMessageConverters(Lists.newArrayList(new MappingJackson2HttpMessageConverter())). This is inconvenient if the instance is shared (as a Spring bean for example) as you might need converter X in one case and converter Y in a different one.

Option 2

You can set Accept and Content-Type HTTP headers explicitly in which case Spring will use a matching message converter. The downside is that you have to resort to instead of RestTemplate.postForEntity which means: extra code, less convenience.

HttpHeaders requestHeaders = new HttpHeaders();
HttpEntity requestEntity = new HttpEntity(entity, requestHeaders);, HttpMethod.POST, requestEntity, Void.class);

Option 3

This might be what I’m looking for 🙂



According to the Spring javadoc ( you can still use postForEntity,

public <T> ResponseEntity<T> postForEntity(java.lang.String url,
                                       java.lang.Object request,
                                       java.lang.Class<T> responseType,
                                       java.util.Map<java.lang.String,?> uriVariables)
                                throws RestClientException

The request parameter can be a HttpEntity in order to add additional HTTP headers to the request.