title: Spring RestTemplate message converter priority when posting
body: <p>What is the most convenient way to influence the priority of the message converters Spring applies when POSTing with <code>RestTemplate</code>?</p>
  
  <p>Use case: I want to ensure a given entity is POSTed as JSON rather than e.g. XML when I do <code>restTemplate.postForEntity(url, entity, Void.class)</code>.</p>
  
  <p><strong>Default</strong></p>
  
  <p>By default the entity is converted to XML because the <code>MappingJackson2XmlHttpMessageConverter</code> takes precedence over the <code>MappingJackson2HttpMessageConverter</code>. The default list of converters for my app appears to be (Spring scans the classpath to see what's available):
  <a href="https://i.stack.imgur.com/TzVFC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TzVFC.png" alt="enter image description here"></a></p>
  
  <p><strong>Option 1</strong></p>
  
  <p>You can configure the message converters explicitly for a given <code>RestTemplate</code> instance like so <code>restTemplate.setMessageConverters(Lists.newArrayList(new MappingJackson2HttpMessageConverter()))</code>. 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.</p>
  
  <p><strong>Option 2</strong></p>
  
  <p>You can set <code>Accept</code> and <code>Content-Type</code> HTTP headers explicitly in which case Spring will use a matching message converter. The downside is that you have to resort to <code>RestTemplate.exchange</code> instead of <code>RestTemplate.postForEntity</code> which means: extra code, less convenience.</p>
  
  <pre><code>HttpHeaders requestHeaders = new HttpHeaders();
  requestHeaders.setContentType(MediaType.APPLICATION_JSON);
  requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
  HttpEntity requestEntity = new HttpEntity(entity, requestHeaders);
  restTemplate.exchange(url, HttpMethod.POST, requestEntity, Void.class);
  </code></pre>
  
  <p><strong>Option 3</strong></p>
  
  <p>This might be what I'm looking for :)</p>