forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaitAllResponsesDisplayBodies.java
More file actions
53 lines (43 loc) · 2.01 KB
/
Copy pathWaitAllResponsesDisplayBodies.java
File metadata and controls
53 lines (43 loc) · 2.01 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package modern.challenge;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class WaitAllResponsesDisplayBodies {
public void waitAllResponses()
throws URISyntaxException, InterruptedException, ExecutionException {
List<URI> uris = Arrays.asList(
new URI("https://reqres.in/api/users/2"), // one user
new URI("https://reqres.in/api/users?page=2"), // list of users
new URI("https://reqres.in/api/unknown/2"), // list of resources
new URI("https://reqres.in/api/users/23")); // single user not foud
HttpClient client = HttpClient.newHttpClient();
List<HttpRequest> requests = uris.stream()
.map(HttpRequest::newBuilder)
.map(reqBuilder -> reqBuilder.build())
.collect(Collectors.toList());
CompletableFuture.allOf(requests.stream()
.map(req -> client.sendAsync(req, HttpResponse.BodyHandlers.ofString())
.thenApply((res) -> res.uri() + " | " + res.body() + "\n")
.exceptionally(e -> "Exception: " + e)
.thenAccept(System.out::println))
.toArray(CompletableFuture<?>[]::new))
.join();
// or, written like this
/*
CompletableFuture<?>[] responses = requests.stream()
.map(req -> client.sendAsync(req, HttpResponse.BodyHandlers.ofString())
.thenApply((res) -> res.uri() + " | " + res.body() + "\n")
.exceptionally(e -> "Exception: " + e)
.thenAccept(System.out::println))
.toArray(CompletableFuture<?>[]::new);
CompletableFuture.allOf(responses).join();
*/
}
}