【问题标题】:Spring RestTemplate not workingSpring RestTemplate 不起作用
【发布时间】: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


【解决方案1】:

您需要将application/octet-stream 添加到MappingJackson2HttpMessageConverter 中支持的mimetypes 列表中:

final MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);

【讨论】:

    猜你喜欢
    • 2017-10-10
    • 1970-01-01
    • 2020-03-25
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2013-09-03
    • 2020-07-19
    相关资源
    最近更新 更多