0

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.

Rajeshwaran R
  • 35
  • 1
  • 5

1 Answers1

2

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);
    }
}
ok2c
  • 26,450
  • 5
  • 63
  • 71