Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we make asynchronous REST api call in Java?

I am using Spring RestTemplate and want to make a call to another service that doesn't return any response body. So, I don't want to wait for the response. So, it's just fire and forget, and continue with the remaining code. I am thinking of creating a new Thread to do this but really not sure what's the correct approach.

like image 631
user10937286 Avatar asked Mar 08 '26 19:03

user10937286


1 Answers

If you use Java 11, java support asynchronous HTTP Client. Asynchronous client using CompletableFuture in the back. You can see javadoc.

HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("http://openjdk.java.net/"))
            .timeout(Duration.ofMinutes(1))
            .header("Content-Type", "application/json")
            .POST(BodyPublishers.ofFile(Paths.get("file.json")))
            .build();

    client.sendAsync(request, BodyHandlers.ofString())
            .thenApply(response -> { System.out.println(response.statusCode());
                return response; } )
            .thenApply(HttpResponse::body)
            .thenAccept(System.out::println);
like image 152
Turac Avatar answered Mar 10 '26 09:03

Turac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!