【发布时间】:2015-12-22 10:08:19
【问题描述】:
我在 Spring 中使用 RestTemplate 创建了应用程序,使用 Rest-Template 我正在使用一个外部 Web 服务,该服务的标头为 Accept 为“application/json”。在我的 Rest-Template 中,我添加了标题,但它仍然给了我以下异常
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.site.Employee] and content type [application/octet-stream]
我的代码如下所示
private static String BASE_URI = "http://localhost:8181/test/employee"
final HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
requestHeaders.setContentType(new MediaType("application", "json"));
final HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
final RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
final ResponseEntity<Employee> responseEntity = restTemplate.exchange(BASE_URI, HttpMethod.GET, requestEntity, Employee.class);
谁能告诉我一些解决方法
更新 1
当我尝试下面的代码时,它工作正常
final ResponseEntity<String> responseEntity = restTemplate.exchange(BASE_URI, HttpMethod.GET, requestEntity, String.class);
Employee employee = new ObjectMapper().readValue(responseEntity.getBody(), Employee.class);
【问题讨论】:
-
您确定远程服务器返回有效的 json 吗?因为
application/octet-stream表示二进制响应。 -
@ksokol 它返回有效的json,当我在邮递员中尝试标题为
Accept和值为application/json时,它给了我一个有效的json。我在几个休息电话中有很多这样的休息电话,其中 json 有一些二进制值,这会产生任何问题 -
响应中
Content-Type的值是多少?我假设它是application/octet-stream。为了完整起见,您能否发布一个带有二进制数据的 json 响应示例? -
@ksokol 如何找到响应的 Content-Type,我已经在 Update2 中发布了我的响应 json
-
@AlexMan 外部网络服务应该有“Produces”应用程序/json。
标签: java spring resttemplate spring-rest