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