Régis Ramillien
Régis Ramillien

Reputation: 335

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 !

Upvotes: 3

Views: 4200

Answers (1)

Pavel Dudin
Pavel Dudin

Reputation: 11

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.

}

Upvotes: 1

Related Questions