Pijotrek
Pijotrek

Reputation: 3021

Java - AsyncHttpClient - aborting ongoing asynchronous call

I am using HttpAsyncClient in order to GET some urls. In some cases, let's say when I receive status HTTP-304, I would like to abandon the ongoing call. I don't want to wait for body, I don't want to spend the machine resources on it. Is there any way of cancelling this? Apparently things like futureResponse.cancel(true) or futureResponse.finalize() do not work.

Future<Response> futureResponse = httpClient.prepareGet("some-url").addHeader("some", "header").execute(new AsyncCompletionHandler<Response>() {
    @Override
    public State onStatusReceived(HttpResponseStatus status) throws Exception {
        logger.info("status {}", status);
        // CONDITIONAL FINISH THIS CALL
        return super.onStatusReceived(status);
    }

    @Override
    public Response onCompleted(Response response) throws Exception {
        logger.info("its ok");
        return response;
    }

    @Override
    public void onThrowable(Throwable t) {
        logger.error(t);
    }
});

Upvotes: 1

Views: 206

Answers (1)

xingbin
xingbin

Reputation: 28289

From the doc:

You can return ABORT to close the connection.

    @Override
    public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
        Integer status = responseStatus.getStatusCode();
        if (304 == status) {  // CONDITIONAL FINISH THIS CALL
            return State.ABORT;
        } else {
            doSomething()
            return ...
        }           
    }

Upvotes: 1

Related Questions