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.client5.http.examples;
28  
29  import java.util.concurrent.CountDownLatch;
30  import java.util.concurrent.Future;
31  
32  import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
33  import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
34  import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
35  import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
36  import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
37  import org.apache.hc.client5.http.config.TlsConfig;
38  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
39  import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
40  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
41  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
42  import org.apache.hc.core5.concurrent.FutureCallback;
43  import org.apache.hc.core5.http.HttpHost;
44  import org.apache.hc.core5.http.message.StatusLine;
45  import org.apache.hc.core5.http2.HttpVersionPolicy;
46  import org.apache.hc.core5.io.CloseMode;
47  import org.apache.hc.core5.reactor.IOReactorConfig;
48  import org.apache.hc.core5.util.Timeout;
49  
50  /**
51   * Example of asynchronous HTTP/1.1 request execution with message exchange multiplexing
52   * over HTTP/2 connections.
53   */
54  public class AsyncClientH2Multiplexing {
55  
56      public static void main(final String[] args) throws Exception {
57  
58          final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
59                  .setSoTimeout(Timeout.ofSeconds(5))
60                  .build();
61  
62          final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder.create()
63                  .setDefaultTlsConfig(TlsConfig.custom()
64                          .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2)
65                          .build())
66                  .setMessageMultiplexing(true)
67                  .build();
68  
69          final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
70                  .setConnectionManager(connectionManager)
71                  .setIOReactorConfig(ioReactorConfig)
72                  .build();
73  
74          client.start();
75  
76          final HttpHost target = new HttpHost("https", "nghttp2.org");
77  
78          final SimpleHttpRequest warmup = SimpleRequestBuilder.get()
79                  .setHttpHost(target)
80                  .setPath("/httpbin")
81                  .build();
82  
83          // Make sure there is an open HTTP/2 connection in the pool
84          System.out.println("Executing warm-up request " + warmup);
85          final Future<SimpleHttpResponse> future = client.execute(
86                  SimpleRequestProducer.create(warmup),
87                  SimpleResponseConsumer.create(),
88                  new FutureCallback<SimpleHttpResponse>() {
89  
90                      @Override
91                      public void completed(final SimpleHttpResponse response) {
92                          System.out.println(warmup + "->" + new StatusLine(response));
93                          System.out.println(response.getBody());
94                      }
95  
96                      @Override
97                      public void failed(final Exception ex) {
98                          System.out.println(warmup + "->" + ex);
99                      }
100 
101                     @Override
102                     public void cancelled() {
103                         System.out.println(warmup + " cancelled");
104                     }
105 
106                 });
107         future.get();
108 
109         Thread.sleep(1000);
110 
111         System.out.println("Connection pool stats: " + connectionManager.getTotalStats());
112 
113         // Execute multiple requests over the HTTP/2 connection from the pool
114         final String[] requestUris = new String[]{"/httpbin", "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
115         final CountDownLatch countDownLatch = new CountDownLatch(requestUris.length);
116 
117         for (final String requestUri : requestUris) {
118             final SimpleHttpRequest request = SimpleRequestBuilder.get()
119                     .setHttpHost(target)
120                     .setPath(requestUri)
121                     .build();
122 
123             System.out.println("Executing request " + request);
124             client.execute(
125                     SimpleRequestProducer.create(request),
126                     SimpleResponseConsumer.create(),
127                     new FutureCallback<SimpleHttpResponse>() {
128 
129                         @Override
130                         public void completed(final SimpleHttpResponse response) {
131                             countDownLatch.countDown();
132                             System.out.println(request + "->" + new StatusLine(response));
133                             System.out.println(response.getBody());
134                         }
135 
136                         @Override
137                         public void failed(final Exception ex) {
138                             countDownLatch.countDown();
139                             System.out.println(request + "->" + ex);
140                         }
141 
142                         @Override
143                         public void cancelled() {
144                             countDownLatch.countDown();
145                             System.out.println(request + " cancelled");
146                         }
147 
148                     });
149         }
150 
151         countDownLatch.await();
152 
153         // There still should be a single connection in the pool
154         System.out.println("Connection pool stats: " + connectionManager.getTotalStats());
155 
156         System.out.println("Shutting down");
157         client.close(CloseMode.GRACEFUL);
158     }
159 
160 }