3

I created this restTemplate bean..

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder              
            .messageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter()))              
            .build();
}

as you can see i set the messageConverter.

but when i used the bean inside my service class ... i get an error like this

"RestClientException: Could not write request: no suitable HttpMessageConverter found for request type . . "

here is the code in my service class . .

ResponseEntity<ProcessGroupEntity> response = this.restTemplate.exchange(RequestEntity.post(new URI(uri))
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(foo)
            , Foo.class);

now i tried setting message converter before calling exchange.

this.restTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter()));

    ResponseEntity<ProcessGroupEntity> response = this.restTemplate.exchange(RequestEntity.post(new URI(uri))
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(foo)
            , Foo.class);

and the code works. so my question is why RestTemplateBuilder's messageConverter() method seems to fail in setting/adding the converter.?

edit:

here is how i inject the restTemplate bean in my service class

private final RestTemplate restTemplate;
...

@Autowired
public SomeService(RestTemplate restTemplate,
                      ...) {

    this.restTemplate = restTemplate;
}
tuty_fruity
  • 523
  • 1
  • 5
  • 18
  • How are you instantiating the `RestTemplate` in your service class? – rorschach Aug 17 '17 at 06:45
  • @rorschach i used contructor injection – tuty_fruity Aug 17 '17 at 06:51
  • 1
    You don't need to add that converter, it is automatically added if Jackson is on the class path. I suspect the fact that you are adding it is actually destroying the proper detection of which converter to use due to the fact you end up with 2 `MappingJackson2HttpMessageConverter` instead of 1. Setting it directly on the `RestTempate` basically overrides the full list of converters and leaves one. So I would suggest to just remove setting the converter on the `RestTemplateBuilder` at all. – M. Deinum Aug 17 '17 at 07:15

0 Answers0