如何从Jetty的HttpClient获取CompletableFuture?

时间:2018-05-07 15:19:39

标签: jetty completable-future

是否可以使用Jetty发出异步HTTP请求并返回CompletableFuture

我看了the docs,但找不到任何这样做的例子。我找到internal usage of CompletableFuture但我无法弄清楚如何使用公共API访问它。

更新:我还需要CompletableFuture来返回响应正文(而不仅仅是响应代码和标题)。

2 个答案:

答案 0 :(得分:2)

我一直在使用jetty客户端9.4.x

var completable = new CompletableFuture<ContentResponse>();
client
  .newRequest(uri)
  .send(new CompletableFutureResponseListener(completable));

其中

public class CompletableFutureResponseListener extends BufferingResponseListener {
  private final CompletableFuture<ContentResponse> completable;

  public CompletableFutureResponseListener(
      CompletableFuture<ContentResponse> completable) {
    this.completable = completable;
  }

  @Override
  public void onComplete(Result result) {
    if (result.isFailed()) {
      completable.completeExceptionally(result.getFailure());
    } else {
      var response =
          new HttpContentResponse(
              result.getResponse(), 
              getContent(), 
              getMediaType(), 
              getEncoding());
      completable.complete(response);
    }
  }
}

答案 1 :(得分:0)

以这种方式将CompleteListener转换为CompletableFuture非常简单:

CompletableFuture<Result> completable = new Promise.Completable<>();
httpClient.newRequest(...).send(result -> {
    if (result.isFailed()) {
        completable.completeExceptionally(result.getFailure());
    } else {
        completable.complete(result);
    }
});

但是,您可以HttpClient本身完成此操作。跟踪this issue