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