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                  .loadTrustMaterial((chain, authType) -> {
63                      final X509Certificate cert = chain[0];
64                      return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
65                  })
66                  .build();
67          final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
68                  .setSslContext(sslcontext)
69                  .build();
70  
71          final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
72                  .setTlsStrategy(tlsStrategy)
73                  .build();
74          try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
75                  .setConnectionManager(cm)
76                  .build()) {
77  
78              client.start();
79  
80              final HttpHost target = new HttpHost("https", "httpbin.org");
81              final HttpClientContext clientContext = HttpClientContext.create();
82  
83              final SimpleHttpRequest request = SimpleRequestBuilder.get()
84                      .setHttpHost(target)
85                      .setPath("/")
86                      .build();
87  
88              System.out.println("Executing request " + request);
89              final Future<SimpleHttpResponse> future = client.execute(
90                      SimpleRequestProducer.create(request),
91                      SimpleResponseConsumer.create(),
92                      clientContext,
93                      new FutureCallback<SimpleHttpResponse>() {
94  
95                          @Override
96                          public void completed(final SimpleHttpResponse response) {
97                              System.out.println(request + "->" + new StatusLine(response));
98                              final SSLSession sslSession = clientContext.getSSLSession();
99                              if (sslSession != null) {
100                                 System.out.println("SSL protocol " + sslSession.getProtocol());
101                                 System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
102                             }
103                             System.out.println(response.getBody());
104                         }
105 
106                         @Override
107                         public void failed(final Exception ex) {
108                             System.out.println(request + "->" + ex);
109                         }
110 
111                         @Override
112                         public void cancelled() {
113                             System.out.println(request + " cancelled");
114                         }
115 
116                     });
117             future.get();
118 
119             System.out.println("Shutting down");
120             client.close(CloseMode.GRACEFUL);
121         }
122     }
123 
124 }