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.nio.ByteBuffer;
30  import java.nio.CharBuffer;
31  import java.util.concurrent.Future;
32  
33  import org.apache.hc.client5.http.async.methods.AbstractBinPushConsumer;
34  import org.apache.hc.client5.http.async.methods.AbstractCharResponseConsumer;
35  import org.apache.hc.client5.http.config.TlsConfig;
36  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
37  import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
38  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
39  import org.apache.hc.core5.function.Supplier;
40  import org.apache.hc.core5.http.ContentType;
41  import org.apache.hc.core5.http.HttpHost;
42  import org.apache.hc.core5.http.HttpRequest;
43  import org.apache.hc.core5.http.HttpResponse;
44  import org.apache.hc.core5.http.impl.routing.RequestRouter;
45  import org.apache.hc.core5.http.message.BasicHttpRequest;
46  import org.apache.hc.core5.http.message.StatusLine;
47  import org.apache.hc.core5.http.nio.AsyncPushConsumer;
48  import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
49  import org.apache.hc.core5.http.support.BasicRequestBuilder;
50  import org.apache.hc.core5.http2.HttpVersionPolicy;
51  import org.apache.hc.core5.http2.config.H2Config;
52  import org.apache.hc.core5.io.CloseMode;
53  
54  /**
55   * This example demonstrates handling of HTTP/2 message exchanges pushed by the server.
56   */
57  public class AsyncClientH2ServerPush {
58  
59      public static void main(final String[] args) throws Exception {
60  
61          final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
62                  .setH2Config(H2Config.custom()
63                          .setPushEnabled(true)
64                          .build())
65                  .setConnectionManager(PoolingAsyncClientConnectionManagerBuilder.create()
66                          .setDefaultTlsConfig(TlsConfig.custom()
67                                  .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2)
68                                  .build())
69                          .build())
70                  .build();
71  
72          client.start();
73  
74          final RequestRouter<Supplier<AsyncPushConsumer>> pushRequestRouter = RequestRouter.<Supplier<AsyncPushConsumer>>builder()
75                  // Route all requests to the local authority
76                  .resolveAuthority(RequestRouter.LOCAL_AUTHORITY_RESOLVER)
77                  // Use the same route for all requests
78                  .addRoute(RequestRouter.LOCAL_AUTHORITY, "*", () -> new AbstractBinPushConsumer() {
79  
80                      @Override
81                      protected void start(
82                              final HttpRequest promise,
83                              final HttpResponse response,
84                              final ContentType contentType) {
85                          System.out.println(promise.getPath() + " (push)->" + new StatusLine(response));
86                      }
87  
88                      @Override
89                      protected int capacityIncrement() {
90                          return Integer.MAX_VALUE;
91                      }
92  
93                      @Override
94                      protected void data(final ByteBuffer data, final boolean endOfStream) {
95                      }
96  
97                      @Override
98                      protected void completed() {
99                      }
100 
101                     @Override
102                     public void failed(final Exception cause) {
103                         System.out.println("(push)->" + cause);
104                     }
105 
106                     @Override
107                     public void releaseResources() {
108                     }
109 
110                 })
111                 .build();
112 
113         final HttpHost target = new HttpHost("https", "nghttp2.org");
114 
115         final BasicHttpRequest request = BasicRequestBuilder.get()
116                 .setHttpHost(target)
117                 .setPath("/httpbin/")
118                 .build();
119 
120         System.out.println("Executing request " + request);
121         final Future<Void> future = client.execute(
122                 new BasicRequestProducer(request, null),
123                 new AbstractCharResponseConsumer<Void>() {
124 
125                     @Override
126                     protected void start(
127                             final HttpResponse response,
128                             final ContentType contentType) {
129                         System.out.println(request + "->" + new StatusLine(response));
130                     }
131 
132                     @Override
133                     protected int capacityIncrement() {
134                         return Integer.MAX_VALUE;
135                     }
136 
137                     @Override
138                     protected void data(final CharBuffer data, final boolean endOfStream) {
139                     }
140 
141                     @Override
142                     protected Void buildResult() {
143                         return null;
144                     }
145 
146                     @Override
147                     public void failed(final Exception cause) {
148                         System.out.println(request + "->" + cause);
149                     }
150 
151                     @Override
152                     public void releaseResources() {
153                     }
154 
155                 },
156                 HttpAsyncClients.pushRouter(pushRequestRouter),
157                 null,
158                 null);
159         future.get();
160 
161         System.out.println("Shutting down");
162         client.close(CloseMode.GRACEFUL);
163     }
164 
165 }