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
- Create an Asynchronous Request: Use
HttpClient.sendAsync
to initiate the HTTP request asynchronously. This returns aCompletableFuture
. - Cancel the Request: Use
CompletableFuture.cancel(true)
to cancel the request. Thetrue
parameter interrupts the thread performing the computation if it is running. - Handle Cancellation or Completion: Use
whenComplete
on theCompletableFuture
to handle the scenario where the operation is either cancelled or successfully completed. - 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
- Cancellation Result: The
cancel
method returnstrue
if the cancellation was successful andfalse
if the task could not be cancelled, such as if it was already completed. - Non-blocking Behavior: This approach is non-blocking and makes use of asynchronous programming.