考虑以下示例:
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;
}
}
在标记为???
的位置,我不知道要调用哪种方法才能将响应正文作为InputStream
接收。
request.asObject(InputStream.class)
之类的东西不起作用,因为此方法使用对象映射器将响应封送至Java类中(InputStream
中当然没有一个)。
答案 0 :(得分:1)
您可以像这样获得原始响应输入流:
HttpResponse<InputStream> response = request.asObject(raw -> raw.getContent());
InputStream responseInputStream = response.getBody();
如果您要求在执行lambda之后不立即关闭输入流,则需要使用async方法:
CompletableFuture<HttpResponse<InputStream>> responseFuture = request.asObjectAsync(raw -> raw.getContent());
HttpResponse<InputStream> response = responseFuture.get();
InputStream responseInputStream = response.getBody();