拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 使用restTemplate下载内容型别八位字节流的档案

使用restTemplate下载内容型别八位字节流的档案

白鹭 - 2022-02-13 2165 0 0

在我的应用程序中,我从 API 回应中接收到一个档案,该档案Content-Typeapplication/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]

通过浏览一些档案,我想到了使用responseEntityExtractorRestTemplate.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 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *