英文:
Consuming a StreamingResponseBody with Spring
问题
我有一个简单的 Web 服务,使用 StreamingResponseBody 流式传输文件。定义如下:
@GetMapping("/files/{filename}")
public ResponseEntity<StreamingResponseBody> download(@PathVariable String filename) {
...
StreamingResponseBody responseBody = out -> {
...
};
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentLength(byteArray.length);
return new ResponseEntity(responseBody, httpHeaders, HttpStatus.OK);
}
它工作得很好,但现在,我需要在客户端应用程序中使用它。我正在使用 Spring 进行消费,但我找不到一种在流传输的同时将其读取并写入文件的方法...
我尝试使用 Feign,但似乎不支持它。
我尝试使用 RestTemplate,但无法使其工作...
Spring 是否支持客户端流式传输?
有人知道如何做到这一点吗?
也许可以使用纯 Java API?
非常感谢您的帮助!
英文:
I've got a simple web-service that stream a file using a StreamingResponseBody.
The definition looks like this:
@GetMapping("/files/{filename}")
public ResponseEntity<StreamingResponseBody> download(@PathVariable String filename) {
...
StreamingResponseBody responseBody = out -> {
...
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentLength(byteArray.length);
return new ResponseEntity(responseBody, httpHeaders, HttpStatus.OK);
}
It works well, but now, I need to consume it in a client application.
I'm using spring to consume it, but I can't find a way to read the stream and write it to a file as it flows...
I tryied using feign but it seems it doesn't support it.
I tryied using restTemplate but I can't make it work...
Does spring support streaming client side ?
Does anybody know how to do this ?
Perhaps using pure java API ?
Thanks a lot for your help !
答案1
得分: 1
你可以使用Apache Http Client(org.apache.httpcomponents:httpclient:4.5.12):
URI uri = new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPort(port)
.setPath(url)
.build();
HttpUriRequest request = RequestBuilder.get(uri).build();
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpClient.execute(request);
InputStream inputStream = httpResponse.getEntity().getContent()) {
// 随意处理流,例如可以使用FileOutputStream将其写入文件,使用上述的 'inputStream'。
}
英文:
You can use Apache Http Client (org.apache.httpcomponents:httpclient:4.5.12):
URI uri = new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setPort(port)
.setPath(url)
.build();
HttpUriRequest request = RequestBuilder.get(uri).build();
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpClient.execute(request);
InputStream inputStream = httpResponse.getEntity().getContent()) {
// Do with stream whatever you want, for example put it to File using FileOutputStream and 'inputStream' above.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论