View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.http.examples;
28  
29  import java.security.cert.CertificateException;
30  import java.security.cert.X509Certificate;
31  import java.util.concurrent.Future;
32  
33  import javax.net.ssl.SSLContext;
34  import javax.net.ssl.SSLSession;
35  
36  import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
37  import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
38  import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
39  import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
40  import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
41  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
42  import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
43  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
44  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
45  import org.apache.hc.client5.http.protocol.HttpClientContext;
46  import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
47  import org.apache.hc.core5.concurrent.FutureCallback;
48  import org.apache.hc.core5.http.HttpHost;
49  import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
50  import org.apache.hc.core5.io.CloseMode;
51  import org.apache.hc.core5.ssl.SSLContexts;
52  import org.apache.hc.core5.ssl.TrustStrategy;
53  
54  /**
55   * This example demonstrates how to create secure connections with a custom SSL
56   * context.
57   */
58  public class AsyncClientCustomSSL {
59  
60      public static void main(final String[] args) throws Exception {
61          // Trust standard CA and those trusted by our custom strategy
62          final SSLContext sslcontext = SSLContexts.custom()
63                  .loadTrustMaterial(new TrustStrategy() {
64  
65                      @Override
66                      public boolean isTrusted(
67                              final X509Certificate[] chain,
68                              final String authType) throws CertificateException {
69                          final X509Certificate cert = chain[0];
70                          return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
71                      }
72  
73                  })
74                  .build();
75          final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
76                  .setSslContext(sslcontext)
77                  // IMPORTANT uncomment the following method when running Java 9 or older
78                  // in order for ALPN support to work and avoid the illegal reflective
79                  // access operation warning
80                  /*
81                  .setTlsDetailsFactory(new Factory<SSLEngine, TlsDetails>() {
82  
83                      @Override
84                      public TlsDetails create(final SSLEngine sslEngine) {
85                          return new TlsDetails(sslEngine.getSession(), sslEngine.getApplicationProtocol());
86                      }
87                  })
88                  */
89                  .build();
90  
91          final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
92                  .setTlsStrategy(tlsStrategy)
93                  .build();
94          try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
95                  .setConnectionManager(cm)
96                  .build()) {
97  
98              client.start();
99  
100             final HttpHost target = new HttpHost("https", "httpbin.org", 443);
101             final String requestUri = "/";
102             final HttpClientContext clientContext = HttpClientContext.create();
103 
104             final SimpleHttpRequest request = SimpleHttpRequests.get(target, requestUri);
105             final Future<SimpleHttpResponse> future = client.execute(
106                     SimpleRequestProducer.create(request),
107                     SimpleResponseConsumer.create(),
108                     clientContext,
109                     new FutureCallback<SimpleHttpResponse>() {
110 
111                         @Override
112                         public void completed(final SimpleHttpResponse response) {
113                             System.out.println(requestUri + "->" + response.getCode());
114                             System.out.println(response.getBody());
115                             final SSLSession sslSession = clientContext.getSSLSession();
116                             if (sslSession != null) {
117                                 System.out.println("SSL protocol " + sslSession.getProtocol());
118                                 System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
119                             }
120                         }
121 
122                         @Override
123                         public void failed(final Exception ex) {
124                             System.out.println(requestUri + "->" + ex);
125                         }
126 
127                         @Override
128                         public void cancelled() {
129                             System.out.println(requestUri + " cancelled");
130                         }
131 
132                     });
133             future.get();
134 
135             System.out.println("Shutting down");
136             client.close(CloseMode.GRACEFUL);
137         }
138     }
139 
140 }