resttemplate getForObject map responsetype
更新 02/05/2018 (大约4年后)...我再次测试了这一点,因为人们一直在投票我的问题/答案,而Sotirios Delimanolis是正确的,我不应该在我的答案中编写代码来使这项工作。我基本上使用了相同的 RestTemplate/REST 服务设置,如我的问题所示,REST 服务具有已确认的响应内容类型 application/json,RestTemplate 能够毫无问题地将响应处理到 Map 中。
我正在调用一个返回如下的 rest 服务:JSON
{
"some.key" : "some value",
"another.key" : "another value"
}
我想我想我可以用a作为响应类型调用这个服务,但这对我不起作用。我得到这个例外:java.util.Map
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map]
我应该只指定为响应类型并将 转换为 ?String
JSON
Map
编辑 I
这是我的 restTemplate 调用:
private Map<String, String> getBuildInfo(String buildUrl) {
return restTemplate.getForObject(buildUrl, Map.class);
}
以下是我设置 restTemplate 的方法:
@PostConstruct
public void initialize() {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
requestWrapper.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
return execution.execute(requestWrapper, body);
}
});
restTemplate.setInterceptors(interceptors);
}
编辑二
完整的错误消息:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [application/octet-stream]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:549) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:239) ~[spring-web-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at idexx.ordering.services.AwsServersServiceImpl.getBuildInfo(AwsServersServiceImpl.java:96) ~[classes/:na]