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