LoginSignup
6
6

More than 5 years have passed since last update.

RestTemplateのCould not extract response: no suitable HttpMessageConverter found for response typeの対策

Posted at

環境

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

状況

あるREST APIが場合によってContent-Typeがapplication/jsonになったりapplication/octet-streamするが、JSONが返ってくることには変わりはない状況に出くわした。このとき、レスポンスのJavaオブジェクトへのマッピングがapplication/octet-streamの場合は以下のようにエラーとなる。

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class asdf.springsample.SampleController$MyResponse] and content type [application/octet-stream]

対策

デフォルトではspringのConverterがapplication/jsonの場合にマッピングするようになっているので、これにapplication/octet-streamも追加する。参考:Could not extract response: no suitable HttpMessageConverter found for response type

RestTemplate r = new RestTemplate();

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

RequestEntity<String> request = RequestEntity.post(new URI("http://localhost:8080/a2")).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM).body("");
ResponseEntity<MyResponse> response = r.exchange(request, MyResponse.class);

もしくは、参考URLによると、Apache HttpComponents HttpClientをクラスパスに入れてこっちを使う場合は以下のようなやり方でもOKらしい(こっちは実際に試してない)。

ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
RestTemplate restTemplate = new RestTemplate(requestFactory);
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6