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.X509Certificate;
30  import java.util.concurrent.Future;
31  
32  import javax.net.ssl.SSLContext;
33  import javax.net.ssl.SSLSession;
34  
35  import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
36  import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
37  import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
38  import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
39  import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
40  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
41  import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
42  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
43  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
44  import org.apache.hc.client5.http.protocol.HttpClientContext;
45  import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
46  import org.apache.hc.core5.concurrent.FutureCallback;
47  import org.apache.hc.core5.http.HttpHost;
48  import org.apache.hc.core5.http.message.StatusLine;
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  
53  /**
54   * This example demonstrates how to create secure connections with a custom SSL
55   * context.
56   */
57  public class AsyncClientCustomSSL {
58  
59      public static void main(final String[] args) throws Exception {
60          // Trust standard CA and those trusted by our custom strategy
61          final SSLContext sslContext = SSLContexts.custom()
62                  // Custom TrustStrategy implementations are intended for verification
63                  // of certificates whose CA is not trusted by the system, and where specifying
64                  // a custom truststore containing the certificate chain is not an option.
65                  .loadTrustMaterial((chain, authType) -> {
66                      // Please note that validation of the server certificate without validation
67                      // of the entire certificate chain in this example is preferred to completely
68                      // disabling trust verification, however this still potentially allows
69                      // for man-in-the-middle attacks.
70                      final X509Certificate cert = chain[0];
71                      return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
72                  })
73                  .build();
74          final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
75                  .setSslContext(sslContext)
76                  .build();
77  
78          final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
79                  .setTlsStrategy(tlsStrategy)
80                  .build();
81          try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
82                  .setConnectionManager(cm)
83                  .build()) {
84  
85              client.start();
86  
87              final HttpHost target = new HttpHost("https", "httpbin.org");
88              final HttpClientContext clientContext = HttpClientContext.create();
89  
90              final SimpleHttpRequest request = SimpleRequestBuilder.get()
91                      .setHttpHost(target)
92                      .setPath("/")
93                      .build();
94  
95              System.out.println("Executing request " + request);
96              final Future<SimpleHttpResponse> future = client.execute(
97                      SimpleRequestProducer.create(request),
98                      SimpleResponseConsumer.create(),
99                      clientContext,
100                     new FutureCallback<SimpleHttpResponse>() {
101 
102                         @Override
103                         public void completed(final SimpleHttpResponse response) {
104                             System.out.println(request + "->" + new StatusLine(response));
105                             final SSLSession sslSession = clientContext.getSSLSession();
106                             if (sslSession != null) {
107                                 System.out.println("SSL protocol " + sslSession.getProtocol());
108                                 System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
109                             }
110                             System.out.println(response.getBody());
111                         }
112 
113                         @Override
114                         public void failed(final Exception ex) {
115                             System.out.println(request + "->" + ex);
116                         }
117 
118                         @Override
119                         public void cancelled() {
120                             System.out.println(request + " cancelled");
121                         }
122 
123                     });
124             future.get();
125 
126             System.out.println("Shutting down");
127             client.close(CloseMode.GRACEFUL);
128         }
129     }
130 
131 }