本文介绍了如何通过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:

所以我认为,我需要将响应标头 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);

这篇关于如何通过Spring RestTemplate更改获取请求中的响应HTTP标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 09:55