How do I cancel an ongoing HTTP request using Java 11 HttpClient?

In Java 11, the HttpClient API does not provide an explicit “cancel” method for ongoing HTTP requests, but you can use a java.util.concurrent.Future to achieve cancellation. When you send an asynchronous request using HttpClient in Java 11, the sendAsync method returns a CompletableFuture. You can call cancel on the CompletableFuture to attempt to cancel the ongoing HTTP operation.

Here’s how you can cancel an ongoing HTTP request:

Example Code

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;

public class HttpClientCancelExample {
    public static void main(String[] args) {
        HttpClient client = HttpClient.newHttpClient();

        // Create the HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://httpbin.org/delay/5"))  // A 5-second delay URL
                .GET()
                .build();

        // Send the request asynchronously
        CompletableFuture<HttpResponse<String>> futureResponse =
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());

        // Simulate a need to cancel the request
        try {
            // Wait 2 seconds
            Thread.sleep(2000);
            // Attempt to cancel the request
            boolean cancelResult = futureResponse.cancel(true);

            if (cancelResult) {
                System.out.println("Request was cancelled successfully.");
            } else {
                System.out.println("Request could not be cancelled.");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Handle the original CompletableFuture response (if not cancelled)
        futureResponse.whenComplete((response, throwable) -> {
            if (throwable != null) {
                System.out.println("Request was cancelled or completed with error: " + throwable.getMessage());
            } else {
                System.out.println("Response received: " + response.body());
            }
        });
    }
}

Explanation

  1. Create an Asynchronous Request: Use HttpClient.sendAsync to initiate the HTTP request asynchronously. This returns a CompletableFuture.
  2. Cancel the Request: Use CompletableFuture.cancel(true) to cancel the request. The true parameter interrupts the thread performing the computation if it is running.
  3. Handle Cancellation or Completion: Use whenComplete on the CompletableFuture to handle the scenario where the operation is either cancelled or successfully completed.
  4. Resource Cleanup: If cancellation succeeds, you should be aware that the underlying network connection may not always terminate immediately, as it depends on the implementation.

Things to Note

  1. Cancellation Result: The cancel method returns true if the cancellation was successful and false if the task could not be cancelled, such as if it was already completed.
  2. Non-blocking Behavior: This approach is non-blocking and makes use of asynchronous programming.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.