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 package org.apache.hc.client5.http.examples.fluent;
28
29 import java.util.LinkedList;
30 import java.util.Queue;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.Future;
35
36 import org.apache.hc.client5.http.fluent.Async;
37 import org.apache.hc.client5.http.fluent.Content;
38 import org.apache.hc.client5.http.fluent.Request;
39 import org.apache.hc.core5.concurrent.FutureCallback;
40
41
42
43
44
45 public class FluentAsync {
46
47 public static void main(final String... args)throws Exception {
48
49 final ExecutorService threadpool = Executors.newFixedThreadPool(2);
50 final Async async = Async.newInstance().use(threadpool);
51
52 final Request[] requests = new Request[] {
53 Request.get("http://www.google.com/"),
54 Request.get("http://www.yahoo.com/"),
55 Request.get("http://www.apache.org/"),
56 Request.get("http://www.apple.com/")
57 };
58
59
60 final Queue<Future<Content>> queue = new LinkedList<>();
61
62 for (final Request request: requests) {
63 final Future<Content> future = async.execute(request, new FutureCallback<Content>() {
64
65 @Override
66 public void failed(final Exception ex) {
67 System.out.println(ex.getMessage() + ": " + request);
68 }
69
70 @Override
71 public void completed(final Content content) {
72 System.out.println("Request completed: " + request);
73 }
74
75 @Override
76 public void cancelled() {
77 }
78
79 });
80 queue.add(future);
81 }
82
83 while(!queue.isEmpty()) {
84 final Future<Content> future = queue.remove();
85 try {
86 future.get();
87 } catch (final ExecutionException ex) {
88 }
89 }
90 System.out.println("Done");
91 threadpool.shutdown();
92 }
93
94 }