【问题标题】:Is it possible to abort the http request[GET, POST, etc] in HttpAsynClient from HttpClient-5.x?是否可以从 HttpClient-5.x 中止 HttpAsynClient 中的 http 请求 [GET、POST 等]?
【发布时间】:2020-08-08 13:02:30
【问题描述】:

我正在使用 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】:

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

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

    【讨论】:

    • 谢谢@ok2c,你拯救了我的一天。 :)
    猜你喜欢
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    相关资源
    最近更新 更多