Java - Retrieving Result from OkHttp Asynchronous GET

。_饼干妹妹 提交于 2019-12-01 01:52:17

I'm not a user of Spring Boot, so this is not a complete answer. But if it supports returning a Future, then it's trivial to bridge from OkHttp Callback to a Future.

This may be relevant https://spring.io/guides/gs/async-method/

As for producing the future

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

And then enqueue the job something like

  OkHttpResponseFuture callback = new OkHttpResponseFuture();
  client.newCall(request).enqueue(callback);

  return callback.future.thenApply(response -> {
    try {
      return convertResponse(response);
    } catch (IOException e) {
      throw Throwables.propagate(e);
    } finally {
      response.close();
    }
  });

If you have multiple requests to process you can submit them separately and then wait on all results being available before combining and returning

  public static <T> CompletableFuture<List<T>> join(List<CompletableFuture<T>> futures) {
    CompletableFuture[] cfs = futures.toArray(new CompletableFuture[futures.size()]);

    return CompletableFuture.allOf(cfs)
        .thenApply(v -> combineIndividualResults(c));
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!