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

问题描述 投票:0回答:1

我正在使用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实现此目的?

提前感谢。

apache abort asynchttpclient apache-httpasyncclient apache-httpclient-5.x
1个回答
0
投票

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

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.