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.SimpleHttpResponse;
38  import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
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.message.StatusLine;
50  import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
51  import org.apache.hc.core5.io.CloseMode;
52  import org.apache.hc.core5.ssl.SSLContexts;
53  import org.apache.hc.core5.ssl.TrustStrategy;
54  
55  /**
56   * This example demonstrates how to create secure connections with a custom SSL
57   * context.
58   */
59  public class AsyncClientCustomSSL {
60  
61      public static void main(final String[] args) throws Exception {
62          // Trust standard CA and those trusted by our custom strategy
63          final SSLContext sslcontext = SSLContexts.custom()
64                  .loadTrustMaterial(new TrustStrategy() {
65  
66                      @Override
67                      public boolean isTrusted(
68                              final X509Certificate[] chain,
69                              final String authType) throws CertificateException {
70                          final X509Certificate cert = chain[0];
71                          return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
72                      }
73  
74                  })
75                  .build();
76          final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
77                  .setSslContext(sslcontext)
78                  // IMPORTANT uncomment the following method when running Java 9 or older
79                  // in order for ALPN support to work and avoid the illegal reflective
80                  // access operation warning
81                  /*
82                  .setTlsDetailsFactory(new Factory<SSLEngine, TlsDetails>() {
83  
84                      @Override
85                      public TlsDetails create(final SSLEngine sslEngine) {
86                          return new TlsDetails(sslEngine.getSession(), sslEngine.getApplicationProtocol());
87                      }
88                  })
89                  */
90                  .build();
91  
92          final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
93                  .setTlsStrategy(tlsStrategy)
94                  .build();
95          try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
96                  .setConnectionManager(cm)
97                  .build()) {
98  
99              client.start();
100 
101             final HttpHost target = new HttpHost("https", "httpbin.org");
102             final HttpClientContext clientContext = HttpClientContext.create();
103 
104             final SimpleHttpRequest request = SimpleRequestBuilder.get()
105                     .setHttpHost(target)
106                     .setPath("/")
107                     .build();
108 
109             System.out.println("Executing request " + request);
110             final Future<SimpleHttpResponse> future = client.execute(
111                     SimpleRequestProducer.create(request),
112                     SimpleResponseConsumer.create(),
113                     clientContext,
114                     new FutureCallback<SimpleHttpResponse>() {
115 
116                         @Override
117                         public void completed(final SimpleHttpResponse response) {
118                             System.out.println(request + "->" + new StatusLine(response));
119                             final SSLSession sslSession = clientContext.getSSLSession();
120                             if (sslSession != null) {
121                                 System.out.println("SSL protocol " + sslSession.getProtocol());
122                                 System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
123                             }
124                             System.out.println(response.getBody());
125                         }
126 
127                         @Override
128                         public void failed(final Exception ex) {
129                             System.out.println(request + "->" + ex);
130                         }
131 
132                         @Override
133                         public void cancelled() {
134                             System.out.println(request + " cancelled");
135                         }
136 
137                     });
138             future.get();
139 
140             System.out.println("Shutting down");
141             client.close(CloseMode.GRACEFUL);
142         }
143     }
144 
145 }