我有简单的java spring方法来创建对象
RestTemplate restTemplate = new RestTemplate();
Address address = restTemplate.getForObject(url, Address.class);
但服务器用错误的 Content-Type: text / plain 而不是 application / json (在Postman中检查)回应JSON字符串。我得到了例外:
无法提取响应:找不到合适的HttpMessageConverter用于响应类型[类地址]和内容类型[text / plain; charset = utf-8]
所以我认为,我需要将更改响应头 Content-Type 改为 application / json ,即MappingJackson2HttpMessageConverter找出JSON字符串并运行代码。
答案 0 :(得分:7)
尝试了一个小时之后,我找到了一个简单易行的方法。
默认情况下,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);
答案 1 :(得分:2)
谢谢你的帮助! 如果我无法更改响应的标题。我用右标题创建了新的响应对象。
ClientHttpRequest clientHttpRequest = new SimpleClientHttpRequestFactory().createRequest(URI.create(str), org.springframework.http.HttpMethod.GET);
final ClientHttpResponse clientHttpResponse = clientHttpRequest.execute();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
Address address = new Address();
//It always true, because service always returns 200 OK
if (clientHttpResponse.getStatusCode() == HttpStatus.OK) {
address = (Address) converter.read(address.getClass(), new HttpInputMessage() {
public InputStream getBody() throws IOException {
return clientHttpResponse.getBody();
}
public HttpHeaders getHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(clientHttpResponse.getHeaders());
httpHeaders.put("Content-Type", Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
return httpHeaders;
}
});
busStop.setNearestAddress(address.toString());
}
我确信这不是简单而好的解决方案,但它确实有效。
答案 2 :(得分:0)
要为您的请求设置内容类型,您可以执行以下操作:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<Address> response = restTemplate.exchange(url, HttpMethod.GET, entity, Address.class);
Address address = response.getBody();