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