You can retry requests using the Java 11 HTTP client by composing the returned future with re-schedules in a loop. Here’s an example:
public static <T> CompletableFuture<T> retry(Supplier<CompletableFuture<T>> action, int maxRetries) {
return action.get().handle((result, throwable) -> {
if (throwable != null && maxRetries > 0) {
return retry(action, maxRetries - 1);
} else if (throwable != null) {
throw new RuntimeException(throwable);
} else {
return result;
}
}).thenCompose(Function.identity());
}
This method takes a Supplier that returns a CompletableFuture, and an integer maxRetries that specifies the maximum number of retries. It returns a new CompletableFuture that retries the action if it fails with an exception.
Here’s how you can use this method to retry an HTTP request:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("
http://example.com"))
.build();
CompletableFuture<HttpResponse<String>> response = retry(() -> client.sendAsync(request, HttpResponse.BodyHandlers.ofString()), 3);
This code retries the HTTP request up to three times if it fails with an exception.
I hope this helps! Let me know if you have any other questions.