0

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

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

    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 实现这一点?

提前致谢。

4

1 回答 1

1

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

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);
    }
}
于 2020-04-25T10:46:23.783 回答