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          // Disable 'Expect: Continue' handshake some servers cannot handle well
77          final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
78                  .setIOReactorConfig(ioReactorConfig)
79                  .setHttpProcessor(HttpProcessors.customClient(null).addLast((HttpRequestInterceptor) (request, entity, context) -> request.removeHeaders(HttpHeaders.EXPECT)).build())
80                  .setStreamListener(new Http1StreamListener() {
81  
82                      @Override
83                      public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
84                          System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
85  
86                      }
87  
88                      @Override
89                      public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
90                          System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
91                      }
92  
93                      @Override
94                      public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
95                          if (keepAlive) {
96                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
97                          } else {
98                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
99                          }
100                     }
101 
102                 })
103                 .create();
104 
105         Runtime.getRuntime().addShutdownHook(new Thread(() -> {
106             System.out.println("HTTP requester shutting down");
107             requester.close(CloseMode.GRACEFUL);
108         }));
109         requester.start();
110 
111         final URI requestUri = new URI("http://httpbin.org/post");
112         final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(requestUri)
113                 .setEntity("stuff")
114                 .build();
115         final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(
116                 new StringAsyncEntityConsumer());
117 
118         final CountDownLatch latch = new CountDownLatch(1);
119         requester.execute(new AsyncClientExchangeHandler() {
120 
121             @Override
122             public void releaseResources() {
123                 requestProducer.releaseResources();
124                 responseConsumer.releaseResources();
125                 latch.countDown();
126             }
127 
128             @Override
129             public void cancel() {
130                 System.out.println(requestUri + " cancelled");
131             }
132 
133             @Override
134             public void failed(final Exception cause) {
135                 System.out.println(requestUri + "->" + cause);
136             }
137 
138             @Override
139             public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
140                 requestProducer.sendRequest(channel, httpContext);
141             }
142 
143             @Override
144             public int available() {
145                 return requestProducer.available();
146             }
147 
148             @Override
149             public void produce(final DataStreamChannel channel) throws IOException {
150                 requestProducer.produce(channel);
151             }
152 
153             @Override
154             public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
155                 System.out.println(requestUri + "->" + response.getCode());
156             }
157 
158             @Override
159             public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
160                 System.out.println(requestUri + "->" + response.getCode());
161                 responseConsumer.consumeResponse(response, entityDetails, httpContext, null);
162             }
163 
164             @Override
165             public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
166                 responseConsumer.updateCapacity(capacityChannel);
167             }
168 
169             @Override
170             public void consume(final ByteBuffer src) throws IOException {
171                 responseConsumer.consume(src);
172             }
173 
174             @Override
175             public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
176                 responseConsumer.streamEnd(trailers);
177             }
178 
179         }, Timeout.ofSeconds(30), HttpCoreContext.create());
180 
181         latch.await(1, TimeUnit.MINUTES);
182         System.out.println("Shutting down I/O reactor");
183         requester.initiateShutdown();
184     }
185 
186 }