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.core5.http2.examples;
28  
29  import java.util.List;
30  import java.util.concurrent.CountDownLatch;
31  import java.util.concurrent.Future;
32  
33  import javax.net.ssl.SSLEngine;
34  import javax.net.ssl.SSLException;
35  
36  import org.apache.hc.core5.concurrent.FutureCallback;
37  import org.apache.hc.core5.http.Header;
38  import org.apache.hc.core5.http.HttpConnection;
39  import org.apache.hc.core5.http.HttpHost;
40  import org.apache.hc.core5.http.HttpResponse;
41  import org.apache.hc.core5.http.Message;
42  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
43  import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
44  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
45  import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
46  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
47  import org.apache.hc.core5.http2.config.H2Config;
48  import org.apache.hc.core5.http2.frame.RawFrame;
49  import org.apache.hc.core5.http2.impl.nio.H2StreamListener;
50  import org.apache.hc.core5.http2.impl.nio.bootstrap.H2RequesterBootstrap;
51  import org.apache.hc.core5.http2.ssl.H2ClientTlsStrategy;
52  import org.apache.hc.core5.io.CloseMode;
53  import org.apache.hc.core5.net.NamedEndpoint;
54  import org.apache.hc.core5.reactor.ssl.SSLSessionVerifier;
55  import org.apache.hc.core5.reactor.ssl.TlsDetails;
56  import org.apache.hc.core5.ssl.SSLContexts;
57  import org.apache.hc.core5.util.Timeout;
58  
59  /**
60   * This example demonstrates how to execute HTTP/2 requests over TLS connections.
61   * <p>
62   * It requires Java runtime with ALPN protocol support (such as Oracle JRE 9 or newer).
63   */
64  public class H2TlsAlpnRequestExecutionExample {
65  
66      public final static void main(final String[] args) throws Exception {
67          // Create and start requester
68          final H2Config h2Config = H2Config.custom()
69                  .setPushEnabled(false)
70                  .build();
71  
72          final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap()
73                  .setH2Config(h2Config)
74                  .setTlsStrategy(new H2ClientTlsStrategy(SSLContexts.createSystemDefault(), new SSLSessionVerifier() {
75  
76                      @Override
77                      public TlsDetails verify(final NamedEndpoint endpoint, final SSLEngine sslEngine) throws SSLException {
78                          // IMPORTANT uncomment the following line when running Java 9 or older
79                          // in order to avoid the illegal reflective access operation warning
80                          // ====
81                          // return new TlsDetails(sslEngine.getSession(), sslEngine.getApplicationProtocol());
82                          // ====
83                          return null;
84                      }
85  
86                  }))
87                  .setStreamListener(new H2StreamListener() {
88  
89                      @Override
90                      public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
91                          for (int i = 0; i < headers.size(); i++) {
92                              System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
93                          }
94                      }
95  
96                      @Override
97                      public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
98                          for (int i = 0; i < headers.size(); i++) {
99                              System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
100                         }
101                     }
102 
103                     @Override
104                     public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
105                     }
106 
107                     @Override
108                     public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
109                     }
110 
111                     @Override
112                     public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
113                     }
114 
115                     @Override
116                     public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
117                     }
118 
119                 })
120                 .create();
121         Runtime.getRuntime().addShutdownHook(new Thread() {
122             @Override
123             public void run() {
124                 System.out.println("HTTP requester shutting down");
125                 requester.close(CloseMode.GRACEFUL);
126             }
127         });
128         requester.start();
129 
130         final HttpHost target = new HttpHost("https", "nghttp2.org", 443);
131         final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
132 
133         final CountDownLatch latch = new CountDownLatch(requestUris.length);
134         for (final String requestUri: requestUris) {
135             final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
136             final AsyncClientEndpoint clientEndpoint = future.get();
137             clientEndpoint.execute(
138                     AsyncRequestBuilder.get()
139                             .setHttpHost(target)
140                             .setPath(requestUri)
141                             .build(),
142                     new BasicResponseConsumer<>(new StringAsyncEntityConsumer()),
143                     new FutureCallback<Message<HttpResponse, String>>() {
144 
145                         @Override
146                         public void completed(final Message<HttpResponse, String> message) {
147                             clientEndpoint.releaseAndReuse();
148                             final HttpResponse response = message.getHead();
149                             final String body = message.getBody();
150                             System.out.println(requestUri + "->" + response.getCode() + " " + response.getVersion());
151                             System.out.println(body);
152                             latch.countDown();
153                         }
154 
155                         @Override
156                         public void failed(final Exception ex) {
157                             clientEndpoint.releaseAndDiscard();
158                             System.out.println(requestUri + "->" + ex);
159                             latch.countDown();
160                         }
161 
162                         @Override
163                         public void cancelled() {
164                             clientEndpoint.releaseAndDiscard();
165                             System.out.println(requestUri + " cancelled");
166                             latch.countDown();
167                         }
168 
169                     });
170         }
171 
172         latch.await();
173         System.out.println("Shutting down I/O reactor");
174         requester.initiateShutdown();
175     }
176 
177 }