Java – How do I use OKHTTP for concurrent network requests?

How do I use OKHTTP for concurrent network requests?… here is a solution to the problem.

How do I use OKHTTP for concurrent network requests?

I’m looking for best practices for making concurrent network requests using the OKHTTP library.

Basically this is what I want to do :

I want to write a method that makes N concurrent network requests to different URLs and returns only when all N requests return.

I’ve considered manually writing Threads and Runnables, etc. to create a set of request pools, but wondered if there was some easier way to do that. So my question is:

  1. Does OKHTTP somehow natively support the concurrent request API?
  2. If not, what is the best way to achieve it?

Solution

OkHttp natively supports efficient asynchronous requests, such as sharing an optimal number of connections.

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

For the second part of the problem, you can use CountdownLatch, or you can bridge to java Futures, such as following

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

Then call

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

OkHttpResponseFuture result = new OkHttpResponseFuture();

call.enqueue(result);

return result.future;
  }

In this case, you can use something like CompletableFuture.allOf method

Note If you use Futures for wrapping, it is easy not to close the Response object on failure.

Related Problems and Solutions