Spring RestTemplate Message Converter Priority Priority

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

Use case: I want this object to be POSTed as JSON, and not, for example. XML when I do restTemplate.postForEntity(url, entity, Void.class) .

Default

By default, the object is converted to XML, because MappingJackson2XmlHttpMessageConverter takes precedence over MappingJackson2HttpMessageConverter . The list of default converters for my application looks like (Spring scans the class path to see what is available): enter image description here

Option 1

You can configure message transformers explicitly for a given RestTemplate instance, for example, restTemplate.setMessageConverters(Lists.newArrayList(new MappingJackson2HttpMessageConverter())) . This is inconvenient if the instance is shared (e.g. Spring bean), as you may need an X converter in one case and a Y converter in another.

Option 2

You can explicitly set the HTTP headers Accept and Content-Type , in which case Spring will use the appropriate message converter. The disadvantage is that you need to resort to RestTemplate.exchange instead of RestTemplate.postForEntity , which means: additional code, less convenience.

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

Option 3

This may be what I'm looking for :)

+5
source share

Source: https://habr.com/ru/post/1274203/


All Articles