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.config.ConnectionConfig;
30 import org.apache.hc.client5.http.config.TlsConfig;
31 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
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.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
35 import org.apache.hc.core5.http.ClassicHttpRequest;
36 import org.apache.hc.core5.http.HttpHost;
37 import org.apache.hc.core5.http.URIScheme;
38 import org.apache.hc.core5.http.io.entity.EntityUtils;
39 import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
40 import org.apache.hc.core5.http.message.StatusLine;
41 import org.apache.hc.core5.http.ssl.TLS;
42 import org.apache.hc.core5.util.TimeValue;
43 import org.apache.hc.core5.util.Timeout;
44
45
46
47
48
49 public class ClientConnectionConfig {
50
51 public final static void main(final String[] args) throws Exception {
52 final PoolingHttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
53 .setConnectionConfigResolver(route -> {
54
55 final HttpHost targetHost = route.getTargetHost();
56 if (route.isSecure()) {
57 return ConnectionConfig.custom()
58 .setConnectTimeout(Timeout.ofMinutes(2))
59 .setSocketTimeout(Timeout.ofMinutes(2))
60 .setValidateAfterInactivity(TimeValue.ofMinutes(1))
61 .setTimeToLive(TimeValue.ofHours(1))
62 .build();
63 } else {
64 return ConnectionConfig.custom()
65 .setConnectTimeout(Timeout.ofMinutes(1))
66 .setSocketTimeout(Timeout.ofMinutes(1))
67 .setValidateAfterInactivity(TimeValue.ofSeconds(15))
68 .setTimeToLive(TimeValue.ofMinutes(15))
69 .build();
70 }
71 })
72 .setTlsConfigResolver(host -> {
73
74 if (host.getSchemeName().equalsIgnoreCase("httpbin.org")) {
75 return TlsConfig.custom()
76 .setSupportedProtocols(TLS.V_1_3)
77 .setHandshakeTimeout(Timeout.ofSeconds(10))
78 .build();
79 } else {
80 return TlsConfig.DEFAULT;
81 }
82 })
83 .build();
84 try (CloseableHttpClient httpclient = HttpClients.custom()
85 .setConnectionManager(cm)
86 .build()) {
87
88 for (final URIScheme uriScheme : URIScheme.values()) {
89 final ClassicHttpRequest request = ClassicRequestBuilder.get()
90 .setHttpHost(new HttpHost(uriScheme.id, "httpbin.org"))
91 .setPath("/headers")
92 .build();
93 System.out.println("Executing request " + request);
94 httpclient.execute(request, response -> {
95 System.out.println("----------------------------------------");
96 System.out.println(request + "->" + new StatusLine(response));
97 EntityUtils.consume(response.getEntity());
98 return null;
99 });
100 }
101 }
102 }
103
104 }