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.client5.http.examples;
28  
29  import java.io.IOException;
30  import java.util.concurrent.CancellationException;
31  import java.util.concurrent.ExecutorService;
32  import java.util.concurrent.Executors;
33  import java.util.concurrent.FutureTask;
34  import java.util.concurrent.TimeUnit;
35  
36  import org.apache.hc.client5.http.classic.methods.HttpGet;
37  import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
38  import org.apache.hc.client5.http.impl.classic.FutureRequestExecutionService;
39  import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
40  import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
41  import org.apache.hc.client5.http.io.HttpClientConnectionManager;
42  import org.apache.hc.client5.http.protocol.HttpClientContext;
43  import org.apache.hc.core5.concurrent.FutureCallback;
44  import org.apache.hc.core5.http.ClassicHttpResponse;
45  import org.apache.hc.core5.http.HttpStatus;
46  import org.apache.hc.core5.http.io.HttpClientResponseHandler;
47  
48  public class ClientWithRequestFuture {
49  
50      public static void main(final String[] args) throws Exception {
51          // the simplest way to create a HttpAsyncClientWithFuture
52          final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
53                  .setMaxConnPerRoute(5)
54                  .setMaxConnTotal(5)
55                  .build();
56          final CloseableHttpClient httpclient = HttpClientBuilder.create()
57                  .setConnectionManager(cm)
58                  .build();
59          final ExecutorService execService = Executors.newFixedThreadPool(5);
60          try (final FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(
61                  httpclient, execService)) {
62              // Because things are asynchronous, you must provide a HttpClientResponseHandler
63              final HttpClientResponseHandler<Boolean> handler = new HttpClientResponseHandler<Boolean>() {
64                  @Override
65                  public Boolean handleResponse(final ClassicHttpResponse response) throws IOException {
66                      // simply return true if the status was OK
67                      return response.getCode() == HttpStatus.SC_OK;
68                  }
69              };
70  
71              // Simple request ...
72              final HttpGet request1 = new HttpGet("http://httpbin.org/get");
73              final FutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
74                      HttpClientContext.create(), handler);
75              final Boolean wasItOk1 = futureTask1.get();
76              System.out.println("It was ok? " + wasItOk1);
77  
78              // Cancel a request
79              try {
80                  final HttpGet request2 = new HttpGet("http://httpbin.org/get");
81                  final FutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
82                          HttpClientContext.create(), handler);
83                  futureTask2.cancel(true);
84                  final Boolean wasItOk2 = futureTask2.get();
85                  System.out.println("It was cancelled so it should never print this: " + wasItOk2);
86              } catch (final CancellationException e) {
87                  System.out.println("We cancelled it, so this is expected");
88              }
89  
90              // Request with a timeout
91              final HttpGet request3 = new HttpGet("http://httpbin.org/get");
92              final FutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
93                      HttpClientContext.create(), handler);
94              final Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
95              System.out.println("It was ok? " + wasItOk3);
96  
97              final FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
98                  @Override
99                  public void completed(final Boolean result) {
100                     System.out.println("completed with " + result);
101                 }
102 
103                 @Override
104                 public void failed(final Exception ex) {
105                     System.out.println("failed with " + ex.getMessage());
106                 }
107 
108                 @Override
109                 public void cancelled() {
110                     System.out.println("cancelled");
111                 }
112             };
113 
114             // Simple request with a callback
115             final HttpGet request4 = new HttpGet("http://httpbin.org/get");
116             // using a null HttpContext here since it is optional
117             // the callback will be called when the task completes, fails, or is cancelled
118             final FutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
119                     HttpClientContext.create(), handler, callback);
120             final Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
121             System.out.println("It was ok? " + wasItOk4);
122         }
123     }
124 }