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