是否可以从 HttpClient-5.x 中止 HttpAsynClient 中的 http 请求 [GET,POST,等]?

Is it possible to abort the http request[GET, POST, etc] in HttpAsynClient from HttpClient-5.x?

我正在使用 org.apache.hc.client5.http.impl.async.HttpAsyncClients.create() 为我的 HTTP/2 请求创建 org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient。我正在寻找一些功能来在从套接字通道读取一些数据后中止请求。

我尝试使用 Future 实例中的 cancel(mayInterruptIfRunning) 方法。但是在中止之后我无法得到响应 headers 和下载的内容。

    Future<SimpleHttpResponse> future = null;
    CloseableHttpAsyncClient httpClient = null;
    try {
        httpClient = httpAsyncClientBuilder.build();
        httpClient.start();
        future = httpClient.execute(target, asyncRequestProducer, SimpleResponseConsumer.create(), null, this.httpClientContext, this);
        future.get(10, TimeUnit.SECONDS);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        httpClient.close(CloseMode.GRACEFUL);
    }

有没有其他方法可以使用 httpclient-5.x 实现此目的?

提前致谢。

当然是。但是您需要实现自己的自定义响应消费者,它可以 return 部分消息内容

try (CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault()) {
    httpClient.start();

    final Future<Void> future = httpClient.execute(
            new BasicRequestProducer(Method.GET, new URI("http://httpbin.org/")),
            new AbstractCharResponseConsumer<Void>() {

                @Override
                protected void start(
                        final HttpResponse response,
                        final ContentType contentType) throws HttpException, IOException {
                    System.out.println(response.getCode());
                }

                @Override
                protected int capacityIncrement() {
                    return Integer.MAX_VALUE;
                }

                @Override
                protected void data(final CharBuffer src, final boolean endOfStream) throws IOException {
                }

                @Override
                protected Void buildResult() throws IOException {
                    return null;
                }

                @Override
                public void releaseResources() {
                }

            }, null, null);
    try {
        future.get(1, TimeUnit.SECONDS);
    } catch (TimeoutException ex) {
        future.cancel(true);
    }
}