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