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.util.concurrent.CountDownLatch;
30  import java.util.concurrent.Future;
31  import java.util.concurrent.TimeUnit;
32  
33  import org.apache.hc.core5.concurrent.FutureCallback;
34  import org.apache.hc.core5.http.HttpConnection;
35  import org.apache.hc.core5.http.HttpHost;
36  import org.apache.hc.core5.http.HttpRequest;
37  import org.apache.hc.core5.http.HttpResponse;
38  import org.apache.hc.core5.http.Message;
39  import org.apache.hc.core5.http.Method;
40  import org.apache.hc.core5.http.impl.Http1StreamListener;
41  import org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap;
42  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
43  import org.apache.hc.core5.http.message.RequestLine;
44  import org.apache.hc.core5.http.message.StatusLine;
45  import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
46  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
47  import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
48  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
49  import org.apache.hc.core5.io.CloseMode;
50  import org.apache.hc.core5.reactor.IOReactorConfig;
51  import org.apache.hc.core5.util.Timeout;
52  
53  /**
54   * Example of asynchronous HTTP/1.1 request execution.
55   */
56  public class AsyncPipelinedRequestExecutionExample {
57  
58      public static void main(final String[] args) throws Exception {
59  
60          final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
61                  .setSoTimeout(5, TimeUnit.SECONDS)
62                  .build();
63  
64          // Create and start requester
65          final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap()
66                  .setIOReactorConfig(ioReactorConfig)
67                  .setStreamListener(new Http1StreamListener() {
68  
69                      @Override
70                      public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
71                          System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
72  
73                      }
74  
75                      @Override
76                      public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
77                          System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
78                      }
79  
80                      @Override
81                      public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
82                          if (keepAlive) {
83                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
84                          } else {
85                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
86                          }
87                      }
88  
89                  })
90                  .create();
91  
92          Runtime.getRuntime().addShutdownHook(new Thread() {
93              @Override
94              public void run() {
95                  System.out.println("HTTP requester shutting down");
96                  requester.close(CloseMode.GRACEFUL);
97              }
98          });
99          requester.start();
100 
101         final HttpHost target = new HttpHost("httpbin.org");
102         final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
103 
104         final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
105         final AsyncClientEndpoint clientEndpoint = future.get();
106 
107         final CountDownLatch latch = new CountDownLatch(requestUris.length);
108         for (final String requestUri: requestUris) {
109             clientEndpoint.execute(
110                     new BasicRequestProducer(Method.GET, target, requestUri),
111                     new BasicResponseConsumer<>(new StringAsyncEntityConsumer()),
112                     new FutureCallback<Message<HttpResponse, String>>() {
113 
114                         @Override
115                         public void completed(final Message<HttpResponse, String> message) {
116                             latch.countDown();
117                             final HttpResponse response = message.getHead();
118                             final String body = message.getBody();
119                             System.out.println(requestUri + "->" + response.getCode());
120                             System.out.println(body);
121                         }
122 
123                         @Override
124                         public void failed(final Exception ex) {
125                             latch.countDown();
126                             System.out.println(requestUri + "->" + ex);
127                         }
128 
129                         @Override
130                         public void cancelled() {
131                             latch.countDown();
132                             System.out.println(requestUri + " cancelled");
133                         }
134 
135                     });
136         }
137 
138         latch.await();
139 
140         // Manually release client endpoint when done !!!
141         clientEndpoint.releaseAndDiscard();
142 
143         System.out.println("Shutting down I/O reactor");
144         requester.initiateShutdown();
145     }
146 
147 }