forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncOneRequest2.java
More file actions
37 lines (29 loc) · 1.24 KB
/
Copy pathAsyncOneRequest2.java
File metadata and controls
37 lines (29 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package modern.challenge;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class AsyncOneRequest2 {
public void triggerOneAyncRequest()
throws IOException, InterruptedException, ExecutionException, TimeoutException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://reqres.in/api/users/2"))
.build();
CompletableFuture<String> response
= client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.exceptionally(e -> "Exception: " + e);
while (!response.isDone()) {
Thread.sleep(50);
System.out.println("Perform other tasks while waiting for the response ...");
}
String body = response.get(30, TimeUnit.SECONDS); // or join()
System.out.println("Body: " + body);
}
}