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 java.security.cert.X509Certificate;
30
31 import javax.net.ssl.SSLContext;
32 import javax.net.ssl.SSLSession;
33
34 import org.apache.hc.client5.http.classic.methods.HttpGet;
35 import org.apache.hc.client5.http.config.TlsConfig;
36 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
37 import org.apache.hc.client5.http.impl.classic.HttpClients;
38 import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
39 import org.apache.hc.client5.http.io.HttpClientConnectionManager;
40 import org.apache.hc.client5.http.protocol.HttpClientContext;
41 import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
42 import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
43 import org.apache.hc.core5.http.io.entity.EntityUtils;
44 import org.apache.hc.core5.http.message.StatusLine;
45 import org.apache.hc.core5.http.ssl.TLS;
46 import org.apache.hc.core5.ssl.SSLContexts;
47 import org.apache.hc.core5.util.Timeout;
48
49
50
51
52
53 public class ClientCustomSSL {
54
55 public final static void main(final String[] args) throws Exception {
56
57 final SSLContext sslContext = SSLContexts.custom()
58
59
60
61 .loadTrustMaterial((chain, authType) -> {
62
63
64
65
66 final X509Certificate cert = chain[0];
67 return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
68 })
69 .build();
70 final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
71 .setSslContext(sslContext)
72 .build();
73
74 final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
75 .setSSLSocketFactory(sslSocketFactory)
76 .setDefaultTlsConfig(TlsConfig.custom()
77 .setHandshakeTimeout(Timeout.ofSeconds(30))
78 .setSupportedProtocols(TLS.V_1_3)
79 .build())
80 .build();
81 try (CloseableHttpClient httpclient = HttpClients.custom()
82 .setConnectionManager(cm)
83 .build()) {
84
85 final HttpGet httpget = new HttpGet("https://httpbin.org/");
86
87 System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
88
89 final HttpClientContext clientContext = HttpClientContext.create();
90 httpclient.execute(httpget, clientContext, response -> {
91 System.out.println("----------------------------------------");
92 System.out.println(httpget + "->" + new StatusLine(response));
93 EntityUtils.consume(response.getEntity());
94 final SSLSession sslSession = clientContext.getSSLSession();
95 if (sslSession != null) {
96 System.out.println("SSL protocol " + sslSession.getProtocol());
97 System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
98 }
99 return null;
100 });
101 }
102 }
103
104 }