如何从Async Http Client请求获取CompletableFuture <t>?

时间:2016-05-25 10:51:00

标签: asynchronous java-8 asynchttpclient completable-future

On Async Http Client documentation我看到如何通过异步HTTP Get请求获取$ behave Tests/BehaveTest* Feature: BehaveTest1 # Tests/BehaveTest1/BehaveTest1.feature:1 Scenario: foo # Tests/BehaveTest1/BehaveTest1.feature:3 When foo # Tests/common.py:3 0.000s Then bar # Tests/common.py:7 0.000s Feature: BehaveTest2 # Tests/BehaveTest2/BehaveTest2.feature:1 Scenario: foo # Tests/BehaveTest2/BehaveTest2.feature:3 When foo # Tests/common.py:3 0.000s Then bar # Tests/common.py:7 0.000s 2 features passed, 0 failed, 0 skipped 2 scenarios passed, 0 failed, 0 skipped 4 steps passed, 0 failed, 0 skipped, 0 undefined Took 0m0.000s ,例如:

Future<Response>

但是,为了方便起见,我希望得到一个AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(); Future<Response> f = asyncHttpClient .prepareGet("http://api.football-data.org/v1/soccerseasons/398") .execute(); Response r = f.get(); ,为此我可以应用一个将结果转换为其他内容的延续,例如将响应内容从Json反序列化为Java对象(例如{ {3}})。这就是我想做的事情:

CompletableFuture<T>

根据SoccerSeason.java,执行此操作的唯一方法是通过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); 对象并使用promise。所以我为此建立了一个Async Http Client documentation

AsyncCompletionHandler<T>

使用这个实用程序方法,我可以重写前面的例子:

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

有没有更好的方法从异步Http客户端请求中获取getDataAsync("http://api.football-data.org/v1/soccerseasons/398") .thenApply(r -> gson.fromJson(r.getResponseBody(), SoccerSeason.class)) .thenAccept(System.out::println);

1 个答案:

答案 0 :(得分:11)

使用AHC2:

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