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