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.http.examples;
28  
29  import java.io.IOException;
30  import java.net.URI;
31  import java.nio.ByteBuffer;
32  import java.util.List;
33  import java.util.concurrent.CountDownLatch;
34  import java.util.concurrent.TimeUnit;
35  
36  import org.apache.hc.core5.http.EntityDetails;
37  import org.apache.hc.core5.http.Header;
38  import org.apache.hc.core5.http.HttpConnection;
39  import org.apache.hc.core5.http.HttpException;
40  import org.apache.hc.core5.http.HttpHeaders;
41  import org.apache.hc.core5.http.HttpRequest;
42  import org.apache.hc.core5.http.HttpRequestInterceptor;
43  import org.apache.hc.core5.http.HttpResponse;
44  import org.apache.hc.core5.http.impl.Http1StreamListener;
45  import org.apache.hc.core5.http.impl.HttpProcessors;
46  import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
47  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
48  import org.apache.hc.core5.http.message.RequestLine;
49  import org.apache.hc.core5.http.message.StatusLine;
50  import org.apache.hc.core5.http.nio.AsyncClientExchangeHandler;
51  import org.apache.hc.core5.http.nio.AsyncRequestProducer;
52  import org.apache.hc.core5.http.nio.CapacityChannel;
53  import org.apache.hc.core5.http.nio.DataStreamChannel;
54  import org.apache.hc.core5.http.nio.RequestChannel;
55  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
56  import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
57  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
58  import org.apache.hc.core5.http.protocol.HttpContext;
59  import org.apache.hc.core5.http.protocol.HttpCoreContext;
60  import org.apache.hc.core5.io.CloseMode;
61  import org.apache.hc.core5.reactor.IOReactorConfig;
62  import org.apache.hc.core5.util.Timeout;
63  
64  /**
65   * Example of full-duplex, streaming HTTP message exchanges with an asynchronous HTTP/1.1 requester.
66   */
67  public class AsyncFullDuplexClientExample {
68  
69      public static void main(final String[] args) throws Exception {
70  
71          final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
72                  .setSoTimeout(5, TimeUnit.SECONDS)
73                  .build();
74  
75          // Create and start requester
76          final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
77                  .setIOReactorConfig(ioReactorConfig)
78                  .setHttpProcessor(HttpProcessors.customClient(null).addLast(new HttpRequestInterceptor() {
79  
80                      // Disable 'Expect: Continue' handshake some servers cannot handle well
81                      @Override
82                      public void process(
83                              final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
84                          request.removeHeaders(HttpHeaders.EXPECT);
85                      }
86  
87                  }).build())
88                  .setStreamListener(new Http1StreamListener() {
89  
90                      @Override
91                      public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
92                          System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
93  
94                      }
95  
96                      @Override
97                      public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
98                          System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
99                      }
100 
101                     @Override
102                     public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
103                         if (keepAlive) {
104                             System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
105                         } else {
106                             System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
107                         }
108                     }
109 
110                 })
111                 .create();
112 
113         Runtime.getRuntime().addShutdownHook(new Thread() {
114             @Override
115             public void run() {
116                 System.out.println("HTTP requester shutting down");
117                 requester.close(CloseMode.GRACEFUL);
118             }
119         });
120         requester.start();
121 
122         final URI requestUri = new URI("http://httpbin.org/post");
123         final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(requestUri)
124                 .setEntity("stuff")
125                 .build();
126         final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(
127                 new StringAsyncEntityConsumer());
128 
129         final CountDownLatch latch = new CountDownLatch(1);
130         requester.execute(new AsyncClientExchangeHandler() {
131 
132             @Override
133             public void releaseResources() {
134                 requestProducer.releaseResources();
135                 responseConsumer.releaseResources();
136                 latch.countDown();
137             }
138 
139             @Override
140             public void cancel() {
141                 System.out.println(requestUri + " cancelled");
142             }
143 
144             @Override
145             public void failed(final Exception cause) {
146                 System.out.println(requestUri + "->" + cause);
147             }
148 
149             @Override
150             public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
151                 requestProducer.sendRequest(channel, httpContext);
152             }
153 
154             @Override
155             public int available() {
156                 return requestProducer.available();
157             }
158 
159             @Override
160             public void produce(final DataStreamChannel channel) throws IOException {
161                 requestProducer.produce(channel);
162             }
163 
164             @Override
165             public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
166                 System.out.println(requestUri + "->" + response.getCode());
167             }
168 
169             @Override
170             public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
171                 System.out.println(requestUri + "->" + response.getCode());
172                 responseConsumer.consumeResponse(response, entityDetails, httpContext, null);
173             }
174 
175             @Override
176             public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
177                 responseConsumer.updateCapacity(capacityChannel);
178             }
179 
180             @Override
181             public void consume(final ByteBuffer src) throws IOException {
182                 responseConsumer.consume(src);
183             }
184 
185             @Override
186             public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
187                 responseConsumer.streamEnd(trailers);
188             }
189 
190         }, Timeout.ofSeconds(30), HttpCoreContext.create());
191 
192         latch.await(1, TimeUnit.MINUTES);
193         System.out.println("Shutting down I/O reactor");
194         requester.initiateShutdown();
195     }
196 
197 }