gpt4 book ai didi

java - 如何在 Unirest 中接收响应体作为 InputStream?

转载 作者:行者123 更新时间:2023-11-30 10:01:46 26 4
gpt4 key购买 nike

考虑以下示例:

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

最佳答案

您可以像这样获取原始响应输入流:

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

关于java - 如何在 Unirest 中接收响应体作为 InputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com