RestTemplate Could not extract response: no suitable HttpMessageConverter found for response type countermeasures

environment

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

Status

I come across a situation where a REST API sometimes has a Content-Type of application / json or application / octet-stream, but JSON is still returned. It was. At this time, if the mapping of the response to the Java object is application / octet-stream, an error will occur as shown below.

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]

Countermeasures

By default, spring Converter is mapped when application / json, so add application / octet-stream to this as well. Reference: [Could not extract response: no suitable HttpMessageConverter found for response type](http://www.technicalkeeda.com/spring-tutorials/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);

Or, according to the reference URL, if you put Apache HttpComponents HttpClient in the classpath and use this, it seems that the following method is also OK (I have not actually tried this).

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

Recommended Posts

RestTemplate Could not extract response: no suitable HttpMessageConverter found for response type countermeasures
[Error resolution] HV000030: No validator could be found for constraint ~ ~