如何发出Java HTTP异步请求?

时间:2020-02-26 11:27:15

标签: java asynchttpclient

通过执行以下代码,我期望立即在控制台上打印"passed",然后3秒后,邮递员的服务器延迟了响应({"delay":"3"}),但是我不得不服务器响应后,请等待3秒钟以查看"passed"的打印结果。我在做什么错了?

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

1 个答案:

答案 0 :(得分:2)

由于@Thilo的提示,我得到了想要的行为。我之前想到的是更像javascript的东西,您可以在其中链接流利的电话并继续前进。在Java中,您可以触发调用,然后在准备阻塞时调用get()join()。因此,它变成了这样:

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