2016-05-25 13 views
5

Ben örneğin, istek basitçe yapıyor Get uyumsuz bir HTTP sonucunda Future<Response> nasıl bakın:Bir Async Http İstemcisi isteğinden nasıl bir CompletableFuture <T> alabilirim? <a href="https://github.com/AsyncHttpClient/async-http-client" rel="nofollow">Async Http Client documentation</a> günü

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

Ancak, kolaylık ben, bunun yerine bir CompletableFuture<T> almak istiyorum hangi I could için Json'dan bir Java nesnesine (örneğin, SoccerSeason.java) yanıt içeriğini serileştirerek örneğin sonucu başka bir şeye dönüştüren bir devam uygulayın. Async Http Client documentation Bunu yapmanın tek yolu göre

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

bir AsyncCompletionHandler<T> nesne ve bir söz kullanarak geçer: Bu yapmak istiyorum şeydir. Sadece yapıyor

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

bu yarar yöntemle ben Önceki örneği yazabilirsiniz::

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

bir zaman uyumsuz Http Client bir CompletableFuture<T> almanın daha iyi bir yolu var mı yüzden bu amaçla bir auxiliary method inşa istek? AHC2 ile

cevap

9

:

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

Eğer [AHC2 Repo] arasında Readme.md' ('bir' CompletableFuture 'kullanım örneği içerir olabilir https://github.com/AsyncHttpClient/async-http-client)? Bence faydalıdır. –

+0

Contribs hoş geldiniz! Gerçekten atm eğlendim. –

İlgili konular