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

眉间皱痕 提交于 2019-12-20 20:41:14

问题


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?


回答1:


With AHC2:

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


来源:https://stackoverflow.com/questions/37434906/how-do-i-get-a-completablefuturet-from-an-async-http-client-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!