Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive the response body as an InputStream in Unirest?

Tags:

java

unirest

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).

like image 970
soc Avatar asked Jan 20 '26 18:01

soc


1 Answers

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();
like image 143
HPCS Avatar answered Jan 22 '26 07:01

HPCS