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