3

Consider the following example:

import java.io.InputStream;
import kong.unirest.GetRequest;
import kong.unirest.HttpResponse;

class Download {
    private long byteCounter;
    private long contentLength;

    InputStream download(GetRequest request) {
        // no appropriate method here? --v
        HttpResponse response = request.??? 

        // get length to display some progress bar later ...
        // (not shown here)
        long contentLength = contentLengthHeader != null
          ? Long.valueOf(contentLengthHeader)
          : Long.valueOf(0);

        InputStream responseInputStream = response.getBody();
        return responseInputStream;
    }
}

At the position marked ??? I can't figure out which method to call to be able to receive the response body as an InputStream.

Something like request.asObject(InputStream.class) doesn't work, as this method uses object-mappers to marshal the response into a Java class (and there of course isn't one for InputStream).

soc
  • 27,983
  • 20
  • 111
  • 215

1 Answers1

3

You can get the raw response input stream like this:

HttpResponse<InputStream> response = request.asObject(raw -> raw.getContent());
InputStream responseInputStream = response.getBody();

If you require that the input stream is not immediately closed after the lambda has been executed, then you need to use the async methods:

CompletableFuture<HttpResponse<InputStream>> responseFuture = request.asObjectAsync(raw -> raw.getContent());
HttpResponse<InputStream> response = responseFuture.get();
InputStream responseInputStream = response.getBody();
soc
  • 27,983
  • 20
  • 111
  • 215
HPCS
  • 1,434
  • 13
  • 22
  • 1
    This doesn't work, as the underlying connection gets released as soon as the lambda has been executed. So yes, technically you can get an `InputStream` from the API this way, but you are pretty much holding a dead corpse. – soc Oct 15 '19 at 17:42
  • `asObjectAsync` also doesn't work, as the `get` call reads the whole `InputStream` into memory, causing out-of-memory errors when retrieving large files. :-( – soc Oct 01 '20 at 08:53