如何在Spring RestTemplate的get请求中更改响应http头?

Dmi*_*hin 6 java spring json

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

RestTemplate restTemplate = new RestTemplate();
Address address = restTemplate.getForObject(url, Address.class);
Run Code Online (Sandbox Code Playgroud)

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

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

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

小智 8

在尝试了一个小时后,我找到了一个简单易行的方法.

默认情况下,Json转换器仅支持" application/json ".我们只是覆盖它以支持" 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);
Run Code Online (Sandbox Code Playgroud)

  • 这就是如何处理转储第三方集成! (2认同)