在我的应用程序中,我从 API 回应中接收到一个档案,该档案Content-Type
是application/octet-stream
.
我正在尝试将此档案作为ResponseEntity<Resource>
.
但我收到错误:
RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class org.springframework.http.ResponseEntity] and content type [application/octet-stream]
通过浏览一些档案,我想到了使用responseEntityExtractor
与RestTemplate.getForEntity相同的档案。
我的代码:
RequestCallback requestCallback = request -> {
HttpHeaders headers1 = request
.getHeaders();
headers1.set("Authorization", "Bearer " template.getAccessToken());
headers1
.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
};
ResponseExtractor<ResponseEntity<Resource>> responseExtractor = template.responseEntityExtractor(ResponseEntity.class);
template.execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
可以理解的是,通过setAccept
在请求回呼中设定,我们让我们restTemplate
知道期望什么型别的内容,responseEntityExtractor()
并将回传ResponseExtractor<ResponseEntity<T>>
。
我错过了什么?
uj5u.com热心网友回复:
代替:
ResponseExtractor<ResponseEntity<Resource>> responseExtractor = template.responseEntityExtractor(ResponseEntity.class);
试试这个byte[]
在控制器方法中回传:
ResponseExtractor<ResponseEntity<byte[]>> responseExtractor = template.responseEntityExtractor(byte[].class);
ResponseEntity<byte[]> results = template.execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
return results.getBody();
或者这个回传ResponseEntity<Resource>
:
ResponseExtractor<ResponseEntity<byte[]>> responseExtractor = template.responseEntityExtractor(byte[].class);
ResponseEntity<byte[]> results = template.execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
ByteArrayResource byteArrayResource = new ByteArrayResource(results.getBody());
return new ResponseEntity<Resource>(byteArrayResource, null, HttpStatus.OK);
0 评论