如何使用OKHTTP发出并发网络请求?

Vla*_*lad 3 java concurrency multithreading android okhttp

我正在寻找使用OKHTTP库进行并发网络请求的最佳实践。

基本上,这就是我想要做的:

我想编写一种方法,使N个并发网络请求发送到不同的URL,并且仅在所有N个请求都返回后才返回。

我考虑过手动编写Threads和Runnables之类的方法来创建一组请求池,但是我想知道是否存在某种更简单的方法来执行此操作。所以我的问题是:

  1. OKHTTP是否以某种方式原生支持并发请求API?
  2. 如果没有,实现此目标的最佳方法是什么?

Yur*_*mke 6

OkHttp本机有效地支持异步请求,例如共享最佳连接数。

参见https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java

对于问题的第二部分,您可以使用CountdownLatch,也可以像下面这样桥接到Java Futures

public class OkHttpResponseFuture implements Callback {
  public final CompletableFuture<Response> future = new CompletableFuture<>();

  public OkHttpResponseFuture() {
  }

  @Override public void onFailure(Call call, IOException e) {
    future.completeExceptionally(e);
  }

  @Override public void onResponse(Call call, Response response) throws IOException {
    future.complete(response);
  }
}
Run Code Online (Sandbox Code Playgroud)

并致电

  private Future<Response> makeRequest(OkHttpClient client, Request request) {
    Call call = client.newCall(request);

    OkHttpResponseFuture result = new OkHttpResponseFuture();

    call.enqueue(result);

    return result.future;
  }
Run Code Online (Sandbox Code Playgroud)

届时,您可以使用CompletableFuture.allOf之类的方法

注意,如果使用Future进行包装,则在失败时不关闭Response对象很容易。