kaiserlautern
kaiserlautern

Reputation: 87

How to make a Java HTTP async request?

By executing the code below, I was expecting to have "passed" printed right away on console and then, 3 seconds later, postman's server delayed response ({"delay":"3"}), but instead I'm having to wait 3 seconds to see "passed" printed, after the server response. What am I doing wrong?

    HttpClient client = HttpClient.newHttpClient();
       HttpRequest request = HttpRequest.newBuilder()
             .uri(URI.create("https://postman-echo.com/delay/3"))
             .header("cache-control", "no-cache")
             .header("postman-token", "6bac0475-7cd1-f51a-945f-2eb772483c2c")
             .build();
       client.sendAsync(request, BodyHandlers.ofString())
             .thenApply(HttpResponse::body)
             .thenAccept(System.out::println)
             .join(); 

       System.out.println("passed");

Upvotes: 1

Views: 2699

Answers (1)

kaiserlautern
kaiserlautern

Reputation: 87

Thank to @Thilo's hints, I got the behavior I was looking for. What I had in mind before was something more like javascript, where you chain up your fluent calls and move ahead. In Java, you trigger the calls and later on, when you're ready to block, you call get() or join(). So, it became like that:

    HttpClient client = HttpClient.newHttpClient();
       HttpRequest request = HttpRequest.newBuilder()
             .uri(URI.create("https://postman-echo.com/delay/3"))
             .header("cache-control", "no-cache")
             .header("postman-token", "6bac0475-7cd1-f51a-945f-2eb772483c2c")
             .build();

       CompletableFuture cf = client.sendAsync(request, BodyHandlers.ofString())
             .thenApply(HttpResponse::body)
             .thenAccept(System.out::println); 

       System.out.println("passed");

       HttpResponse<String> result = (HttpResponse<String>)cf.join();

Upvotes: 2

Related Questions