如何通过Spring RestTemplate更改获取请求中的响应HTTP标头?

问题描述:

我有用于创建对象的简单java spring方法

I have simple java spring method for creating object

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

但是服务器以错误的 Content-Type: 文本/纯文本而不是 application/json 响应了我的JSON字符串(已在Postman中检查) .但我得到了例外:

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:

无法提取响应:找不到适合于响应类型[类地址]和内容类型[text/plain; charset = utf-8]的HttpMessageConverter

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

所以我认为,我需要将响应标头 Content-Type 更改为正确的 application/json ,以便MappingJackson2HttpMessageConverter可以找到JSON字符串并运行代码.

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.

尝试了一个小时之后,我发现了一种简便的方法.

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

Json转换器默认情况下仅支持" application/json ".我们只是重写它以支持" text/plain ".

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