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