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.Method;
40  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
41  import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
42  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
43  import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
44  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
45  import org.apache.hc.core5.http2.HttpVersionPolicy;
46  import org.apache.hc.core5.http2.config.H2Config;
47  import org.apache.hc.core5.http2.frame.RawFrame;
48  import org.apache.hc.core5.http2.impl.nio.H2StreamListener;
49  import org.apache.hc.core5.http2.impl.nio.bootstrap.H2RequesterBootstrap;
50  import org.apache.hc.core5.io.CloseMode;
51  import org.apache.hc.core5.util.Timeout;
52  
53  /**
54   * Example of HTTP/2 request execution.
55   */
56  public class H2RequestExecutionExample {
57  
58      public static void main(final String[] args) throws Exception {
59  
60          // Create and start requester
61          final H2Config h2Config = H2Config.custom()
62                  .setPushEnabled(false)
63                  .build();
64  
65          final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap()
66                  .setH2Config(h2Config)
67                  .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2)
68                  .setStreamListener(new H2StreamListener() {
69  
70                      @Override
71                      public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
72                          for (int i = 0; i < headers.size(); i++) {
73                              System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
74                          }
75                      }
76  
77                      @Override
78                      public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
79                          for (int i = 0; i < headers.size(); i++) {
80                              System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
81                          }
82                      }
83  
84                      @Override
85                      public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
86                      }
87  
88                      @Override
89                      public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
90                      }
91  
92                      @Override
93                      public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
94                      }
95  
96                      @Override
97                      public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
98                      }
99  
100                 })
101                 .create();
102         Runtime.getRuntime().addShutdownHook(new Thread() {
103             @Override
104             public void run() {
105                 System.out.println("HTTP requester shutting down");
106                 requester.close(CloseMode.GRACEFUL);
107             }
108         });
109         requester.start();
110 
111         final HttpHost target = new HttpHost("nghttp2.org");
112         final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
113 
114         final CountDownLatch latch = new CountDownLatch(requestUris.length);
115         for (final String requestUri: requestUris) {
116             final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
117             final AsyncClientEndpoint clientEndpoint = future.get();
118             clientEndpoint.execute(
119                     new BasicRequestProducer(Method.GET, target, requestUri),
120                     new BasicResponseConsumer<>(new StringAsyncEntityConsumer()),
121                     new FutureCallback<Message<HttpResponse, String>>() {
122 
123                         @Override
124                         public void completed(final Message<HttpResponse, String> message) {
125                             clientEndpoint.releaseAndReuse();
126                             final HttpResponse response = message.getHead();
127                             final String body = message.getBody();
128                             System.out.println(requestUri + "->" + response.getCode());
129                             System.out.println(body);
130                             latch.countDown();
131                         }
132 
133                         @Override
134                         public void failed(final Exception ex) {
135                             clientEndpoint.releaseAndDiscard();
136                             System.out.println(requestUri + "->" + ex);
137                             latch.countDown();
138                         }
139 
140                         @Override
141                         public void cancelled() {
142                             clientEndpoint.releaseAndDiscard();
143                             System.out.println(requestUri + " cancelled");
144                             latch.countDown();
145                         }
146 
147                     });
148         }
149 
150         latch.await();
151         System.out.println("Shutting down I/O reactor");
152         requester.initiateShutdown();
153     }
154 
155 }