我正在创建一个宁静的API,它将使用服务器中的json.但是我遇到了异常:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [[Lexamples.dto.DummyDTO;] and content type [text/json;charset=utf-8]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:84)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:454)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:409)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:207)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:189)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
程式码片段:
List<HttpMessageConverter<?>> msgConverters = restTemplate.getMessageConverters();
msgConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(msgConverters);
DummyDTO[] dummy= restTemplate.getForObject(URI, DummyDTO[].class);
控制器方法代码:
public UserDTO[] getUserList(){
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
// Set the Accept and Content type header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(acceptableMediaTypes);
HttpEntity<?> entity = new HttpEntity<Object>(headers);
// Add the Jackson message converter
List<HttpMessageConverter<?>> msgConverters = restTemplate.getMessageConverters();
msgConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(msgConverters);
// Make the HTTP GET request, marshalling the response from JSON to an array of Users
ResponseEntity<UserDTO[]> responseEntity = restTemplate.exchange("http://server.com",HttpMethod.GET, entity, UserDTO[].class);
return responseEntity.getBody();
}
请告诉我我要去哪里错了
解决方法:
看起来您更改了请求的内容类型,但是“ application / json”必须在响应头中,并且您仍然具有相同的异常这一事实表明您在响应中使用了错误的媒体类型“ text / json”,不是这样的media type in HTTP.只需查看restTemplate.exchange(“ http://server.com”,HttpMethod.GET,实体,UserDTO [].class)的实现即可;那里应该是问题.