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

这一生的挚爱 提交于 2021-01-27 18:16:38

问题


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


回答1:


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();


来源:https://stackoverflow.com/questions/57289844/how-to-receive-the-response-body-as-an-inputstream-in-unirest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!