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.CertificateException;
30 import java.security.cert.X509Certificate;
31
32 import javax.net.ssl.SSLContext;
33 import javax.net.ssl.SSLSession;
34
35 import org.apache.hc.client5.http.classic.methods.HttpGet;
36 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
37 import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
38 import org.apache.hc.client5.http.impl.classic.HttpClients;
39 import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
40 import org.apache.hc.client5.http.io.HttpClientConnectionManager;
41 import org.apache.hc.client5.http.protocol.HttpClientContext;
42 import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
43 import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
44 import org.apache.hc.core5.http.io.entity.EntityUtils;
45 import org.apache.hc.core5.http.ssl.TLS;
46 import org.apache.hc.core5.ssl.SSLContexts;
47 import org.apache.hc.core5.ssl.TrustStrategy;
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 .loadTrustMaterial(new TrustStrategy() {
59
60 @Override
61 public boolean isTrusted(
62 final X509Certificate[] chain,
63 final String authType) throws CertificateException {
64 final X509Certificate cert = chain[0];
65 return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
66 }
67
68 })
69 .build();
70
71 final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
72 .setSslContext(sslcontext)
73 .setTlsVersions(TLS.V_1_2)
74 .build();
75 final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
76 .setSSLSocketFactory(sslSocketFactory)
77 .build();
78 try (CloseableHttpClient httpclient = HttpClients.custom()
79 .setConnectionManager(cm)
80 .build()) {
81
82 final HttpGet httpget = new HttpGet("https://httpbin.org/");
83
84 System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
85
86 final HttpClientContext clientContext = HttpClientContext.create();
87 try (CloseableHttpResponse response = httpclient.execute(httpget, clientContext)) {
88 System.out.println("----------------------------------------");
89 System.out.println(response.getCode() + " " + response.getReasonPhrase());
90 System.out.println(EntityUtils.toString(response.getEntity()));
91
92 final SSLSession sslSession = clientContext.getSSLSession();
93 if (sslSession != null) {
94 System.out.println("SSL protocol " + sslSession.getProtocol());
95 System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
96 }
97 }
98 }
99 }
100
101 }