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.util.List;
32  import java.util.concurrent.CountDownLatch;
33  import java.util.concurrent.TimeUnit;
34  
35  import org.apache.hc.client5.http.config.TlsConfig;
36  import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
37  import org.apache.hc.client5.http.impl.async.MinimalHttpAsyncClient;
38  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
39  import org.apache.hc.core5.http.ContentType;
40  import org.apache.hc.core5.http.EntityDetails;
41  import org.apache.hc.core5.http.Header;
42  import org.apache.hc.core5.http.HttpException;
43  import org.apache.hc.core5.http.HttpHost;
44  import org.apache.hc.core5.http.HttpResponse;
45  import org.apache.hc.core5.http.config.Http1Config;
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.AsyncClientExchangeHandler;
49  import org.apache.hc.core5.http.nio.CapacityChannel;
50  import org.apache.hc.core5.http.nio.DataStreamChannel;
51  import org.apache.hc.core5.http.nio.RequestChannel;
52  import org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer;
53  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
54  import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
55  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
56  import org.apache.hc.core5.http.protocol.HttpContext;
57  import org.apache.hc.core5.http.support.BasicRequestBuilder;
58  import org.apache.hc.core5.http2.HttpVersionPolicy;
59  import org.apache.hc.core5.http2.config.H2Config;
60  import org.apache.hc.core5.io.CloseMode;
61  import org.apache.hc.core5.reactor.IOReactorConfig;
62  
63  /**
64   * This example demonstrates a full-duplex, streaming HTTP/2 message exchange.
65   */
66  public class AsyncClientH2FullDuplexExchange {
67  
68      public static void main(final String[] args) throws Exception {
69  
70          final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(
71                  H2Config.DEFAULT,
72                  Http1Config.DEFAULT,
73                  IOReactorConfig.DEFAULT,
74                  PoolingAsyncClientConnectionManagerBuilder.create()
75                          .setDefaultTlsConfig(TlsConfig.custom()
76                                  .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2)
77                                  .build())
78                          .build());
79  
80          client.start();
81  
82          final HttpHost target = new HttpHost("https", "nghttp2.org");
83  
84          final BasicHttpRequest request = BasicRequestBuilder.post()
85                  .setHttpHost(target)
86                  .setPath("/httpbin/post")
87                  .build();
88          final BasicRequestProducer requestProducer = new BasicRequestProducer(request,
89                  new BasicAsyncEntityProducer("stuff", ContentType.TEXT_PLAIN));
90          final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(
91                  new StringAsyncEntityConsumer());
92  
93          System.out.println("Executing request " + request);
94          final CountDownLatch latch = new CountDownLatch(1);
95          client.execute(new AsyncClientExchangeHandler() {
96  
97              @Override
98              public void releaseResources() {
99                  requestProducer.releaseResources();
100                 responseConsumer.releaseResources();
101                 latch.countDown();
102             }
103 
104             @Override
105             public void cancel() {
106                 System.out.println(request + " cancelled");
107             }
108 
109             @Override
110             public void failed(final Exception cause) {
111                 System.out.println(request + "->" + cause);
112             }
113 
114             @Override
115             public void produceRequest(final RequestChannel channel, final HttpContext context) throws HttpException, IOException {
116                 requestProducer.sendRequest(channel, context);
117             }
118 
119             @Override
120             public int available() {
121                 return requestProducer.available();
122             }
123 
124             @Override
125             public void produce(final DataStreamChannel channel) throws IOException {
126                 requestProducer.produce(channel);
127             }
128 
129             @Override
130             public void consumeInformation(
131                     final HttpResponse response,
132                     final HttpContext context) {
133                 System.out.println(request + "->" + new StatusLine(response));
134             }
135 
136             @Override
137             public void consumeResponse(
138                     final HttpResponse response,
139                     final EntityDetails entityDetails,
140                     final HttpContext context) throws HttpException, IOException {
141                 System.out.println(request + "->" + new StatusLine(response));
142                 responseConsumer.consumeResponse(response, entityDetails, context, null);
143             }
144 
145             @Override
146             public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
147                 responseConsumer.updateCapacity(capacityChannel);
148             }
149 
150             @Override
151             public void consume(final ByteBuffer src) throws IOException {
152                 responseConsumer.consume(src);
153             }
154 
155             @Override
156             public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
157                 responseConsumer.streamEnd(trailers);
158             }
159 
160         });
161         latch.await(1, TimeUnit.MINUTES);
162 
163         System.out.println("Shutting down");
164         client.close(CloseMode.GRACEFUL);
165     }
166 
167 }