我有简单的 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/