Search code examples
apacheabortasynchttpclientapache-httpasyncclientapache-httpclient-5.x

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


I'm using org.apache.hc.client5.http.impl.async.HttpAsyncClients.create() to create org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient for my HTTP/2 requests. I'm looking for some functionality to abort the request after reading some amount of data from the socket channel.

i tried with the cancel(mayInterruptIfRunning) method from the Future instance. But after abort it i can't get the response headers and the downloaded content.

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

Is there any other way to achieve this with httpclient-5.x?

Thanks in advance.


Solution

  • Of course, it is. But you need to implement your own custom response consumer that can return a partial message content

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