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;
28
29 import org.apache.hc.client5.http.classic.methods.HttpGet;
30 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
31 import org.apache.hc.client5.http.impl.classic.HttpClients;
32 import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
33 import org.apache.hc.client5.http.protocol.HttpClientContext;
34 import org.apache.hc.core5.http.HttpEntity;
35 import org.apache.hc.core5.http.io.entity.EntityUtils;
36 import org.apache.hc.core5.http.protocol.HttpContext;
37
38
39
40
41
42 public class ClientMultiThreadedExecution {
43
44 public static void main(final String[] args) throws Exception {
45
46
47
48 final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
49 cm.setMaxTotal(100);
50
51 try (final CloseableHttpClient httpclient = HttpClients.custom()
52 .setConnectionManager(cm)
53 .build()) {
54
55 final String[] urisToGet = {
56 "http://hc.apache.org/",
57 "http://hc.apache.org/httpcomponents-core-ga/",
58 "http://hc.apache.org/httpcomponents-client-ga/",
59 };
60
61
62 final GetThread[] threads = new GetThread[urisToGet.length];
63 for (int i = 0; i < threads.length; i++) {
64 final HttpGet httpget = new HttpGet(urisToGet[i]);
65 threads[i] = new GetThread(httpclient, httpget, i + 1);
66 }
67
68
69 for (final GetThread thread : threads) {
70 thread.start();
71 }
72
73
74 for (final GetThread thread : threads) {
75 thread.join();
76 }
77
78 }
79 }
80
81
82
83
84 static class GetThread extends Thread {
85
86 private final CloseableHttpClient httpClient;
87 private final HttpContext context;
88 private final HttpGet httpget;
89 private final int id;
90
91 public GetThread(final CloseableHttpClient httpClient, final HttpGet httpget, final int id) {
92 this.httpClient = httpClient;
93 this.context = HttpClientContext.create();
94 this.httpget = httpget;
95 this.id = id;
96 }
97
98
99
100
101 @Override
102 public void run() {
103 try {
104 System.out.println(id + " - about to get something from " + httpget.getUri());
105 this.httpClient.execute(httpget, response -> {
106 System.out.println(id + " - get executed");
107
108 final HttpEntity entity = response.getEntity();
109 if (entity != null) {
110 final byte[] bytes = EntityUtils.toByteArray(entity);
111 System.out.println(id + " - " + bytes.length + " bytes read");
112 }
113 return null;
114 });
115 } catch (final Exception e) {
116 System.out.println(id + " - error: " + e);
117 }
118 }
119
120 }
121
122 }