How do I get a CompletableFuture<T> from an Async Http Client request?

Miguel Gamboa picture Miguel Gamboa · May 25, 2016 · Viewed 8.6k times · Source

On Async Http Client documentation I see how to get a Future<Response> as the result of an asynchronous HTTP Get request simply doing, for example:

AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
Future<Response> f = asyncHttpClient
      .prepareGet("http://api.football-data.org/v1/soccerseasons/398")
      .execute();
Response r = f.get();

However, for convenience I would like to get a CompletableFuture<T> instead, for which I could apply a continuation that converts the result in something else, for instance deserializing the response content from Json into a Java object (e.g. SoccerSeason.java). This is what I would like to do:

AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
CompletableFuture<Response> f = asyncHttpClient
     .prepareGet("http://api.football-data.org/v1/soccerseasons/398")
     .execute();
f
     .thenApply(r -> gson.fromJson(r.getResponseBody(), SoccerSeason.class))
     .thenAccept(System.out::println);

According to Async Http Client documentation the only way to do this is through an AsyncCompletionHandler<T> object and using a promise. So I built an auxiliary method to that end:

CompletableFuture<Response> getDataAsync(String path){
    CompletableFuture<Response> promise = new CompletableFuture<>();
    asyncHttpClient
            .prepareGet(path)
            .execute(new AsyncCompletionHandler<Response>() {
                @Override
                public Response onCompleted(Response response) throws Exception {
                    promise.complete(response);
                    return response;
                }
                @Override
                public void onThrowable(Throwable t) {
                    promise.completeExceptionally(t);
                }
            });
    return promise;
}

With this utility method I can rewrite the previous example just doing:

getDataAsync("http://api.football-data.org/v1/soccerseasons/398")
    .thenApply(r -> gson.fromJson(r.getResponseBody(), SoccerSeason.class))
    .thenAccept(System.out::println);

Is there any better way of getting a CompletableFuture<T> from an Async Http Client request?

Answer

Stephane Landelle picture Stephane Landelle · May 25, 2016

With AHC2:

CompletableFuture<Response> f = asyncHttpClient
     .prepareGet("http://api.football-data.org/v1/soccerseasons/398")
     .execute()
     .toCompletableFuture();