Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change response http header in get request by spring RestTemplate?

Tags:

java

json

spring

I have simple java spring method for creating object

RestTemplate restTemplate = new RestTemplate();
Address address = restTemplate.getForObject(url, Address.class);

But the server responds me JSON string with wrong Content-Type: text/plain instead of application/json (checked in Postman). And I get the exception:

Could not extract response: no suitable HttpMessageConverter found for response type [class Address] and content type [text/plain;charset=utf-8]

So I think, I need change response header Content-Type to right application/json, that MappingJackson2HttpMessageConverter find out JSON string and run code as well.

like image 833
Dmitry Torshin Avatar asked Mar 04 '17 05:03

Dmitry Torshin


1 Answers

After trying for an hour, I found a short and easy way.

Json converter by default supports only "application/json". We just override it to support "text/plain".

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

// support "text/plain"
converter.setSupportedMediaTypes(Arrays.asList(TEXT_PLAIN, APPLICATION_JSON));

RestTemplate template = new RestTemplate();
template.getMessageConverters().add(converter);

// It's ok now
MyResult result = tmp.postForObject("http://url:8080/api", 
            new MyRequest("param value"), MyResult.class);
like image 102
Neo Pham Avatar answered Oct 06 '22 01:10

Neo Pham