与Spring一起使用StreamingResponseBody

问题描述

我有一个简单的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来消耗它,但是找不到一种方法来读取流并将其写入文件中...

我尝试使用假装,但似乎不支持它。 我尝试使用restTemplate,但是无法正常工作...

spring是否支持流客户端? 有人知道怎么做这个吗 ? 也许使用纯Java API?

非常感谢您的帮助!

解决方法

您可以使用 Apache Http 客户端 (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.

}