gpt4 book ai didi

java - 从多个线程访问 OkHttpClient 响应

转载 作者:行者123 更新时间:2023-12-02 10:09:00 33 4
gpt4 key购买 nike

我想使用PipedOutputStreamPipedInputStream流响应主体。我不太确定它在多线程方面是否安全。将从不同的线程访问响应。


public Streamer execute() {
Response response = null;
try {
Call call = client.newCall(request);
response = call.execute();
return stream(response);
} catch (Exception e) {
if (response != null) response.close();
}
}

@FunctionalInterface
interface Streamer {
void write(OutputStream out) throws Exception;
}

private static Streamer stream(Response response) throws IOException {

return out -> {
// will be executed from a different thread
try (BufferedSource source = response.body().source();
Buffer buffer = new Buffer()) {

BufferedSink sink = Okio.buffer(Okio.sink(out));
long readBytes;
long readTotal = 0;
while ((readBytes = source.read(buffer, BUFFER_SIZE)) != -1) {
sink.write(buffer, readBytes);
sink.flush();
readTotal += readBytes;
}
}
};
}

Response 对象传递给不同的线程并访问 body()body().close() 方法是否安全?

最佳答案

是的!您可以将 Response 对象传递给其他线程。唯一的规则是不能让多个线程同时访问响应正文。

您可能想查看 Okio 中的 Pipe。它比 java.io 管道功能更强一些。

关于java - 从多个线程访问 OkHttpClient 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127830/

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