How can we make asynchronous REST api call in Java?

user10937286 picture user10937286 · May 22, 2019 · Viewed 46.7k times · Source

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.

Answer

Turac picture Turac · May 22, 2019

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);