Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consuming a StreamingResponseBody with Spring

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 !

like image 425
Régis Ramillien Avatar asked Nov 21 '25 06:11

Régis Ramillien


1 Answers

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.

}
like image 135
Pavel Dudin Avatar answered Nov 23 '25 20:11

Pavel Dudin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!