java - 如何通过 spring RestTemplate 更改获取请求中的响应 http header ?

标签 java json spring

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

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

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

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

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

最佳答案

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

默认情况下,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);

关于java - 如何通过 spring RestTemplate 更改获取请求中的响应 http header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42592440/

相关文章:

java - 为我自己的列表创建迭代器时遇到问题

spring - BadCredentialsException : Kerberos validation not succesfull

java - cometd : Cometd servlet does not support asynchronous on tomcat

java - docs.oracle.com 上有关覆盖和隐藏方法的文本是否含糊不清?

java - 如何将 JPanel 转换为文件?

java - Hibernate 尝试将字段值设置为对象

python - 将带有 `\` 的字符串转换为 json 或字典数据

带有连接的 Node.js 中基于 JavaScript 的 JSON 验证器(不是模式,JSON 语法)

java - 使用 Jackson 从 JSON 数组中检索字符串

java - 如何使用 Spring MVC 对上传的文件数量设置最大限制?