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.Future;
30  
31  import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
32  import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
33  import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
34  import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
35  import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
36  import org.apache.hc.client5.http.config.ConnectionConfig;
37  import org.apache.hc.client5.http.config.TlsConfig;
38  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
39  import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
40  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
41  import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
42  import org.apache.hc.core5.concurrent.FutureCallback;
43  import org.apache.hc.core5.http.HttpHost;
44  import org.apache.hc.core5.http.URIScheme;
45  import org.apache.hc.core5.http.message.StatusLine;
46  import org.apache.hc.core5.http.ssl.TLS;
47  import org.apache.hc.core5.io.CloseMode;
48  import org.apache.hc.core5.util.TimeValue;
49  import org.apache.hc.core5.util.Timeout;
50  
51  /**
52   * This example demonstrates how to use connection configuration on a per-route or a per-host
53   * basis.
54   */
55  public class AsyncClientConnectionConfig {
56  
57      public static void main(final String[] args) throws Exception {
58          final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
59                  .setConnectionConfigResolver(route -> {
60                      // Use different settings for all secure (TLS) connections
61                      final HttpHost targetHost = route.getTargetHost();
62                      if (route.isSecure()) {
63                          return ConnectionConfig.custom()
64                                  .setConnectTimeout(Timeout.ofMinutes(2))
65                                  .setSocketTimeout(Timeout.ofMinutes(2))
66                                  .setValidateAfterInactivity(TimeValue.ofMinutes(1))
67                                  .setTimeToLive(TimeValue.ofHours(1))
68                                  .build();
69                      }
70                      return ConnectionConfig.custom()
71                              .setConnectTimeout(Timeout.ofMinutes(1))
72                              .setSocketTimeout(Timeout.ofMinutes(1))
73                              .setValidateAfterInactivity(TimeValue.ofSeconds(15))
74                              .setTimeToLive(TimeValue.ofMinutes(15))
75                              .build();
76                  })
77                  .setTlsConfigResolver(host -> {
78                      // Use different settings for specific hosts
79                      if (host.getSchemeName().equalsIgnoreCase("httpbin.org")) {
80                          return TlsConfig.custom()
81                                  .setSupportedProtocols(TLS.V_1_3)
82                                  .setHandshakeTimeout(Timeout.ofSeconds(10))
83                                  .build();
84                      }
85                      return TlsConfig.DEFAULT;
86                  })
87                  .build();
88          try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
89                  .setConnectionManager(cm)
90                  .build()) {
91  
92              client.start();
93  
94              for (final URIScheme uriScheme : URIScheme.values()) {
95                  final SimpleHttpRequest request = SimpleRequestBuilder.get()
96                          .setHttpHost(new HttpHost(uriScheme.id, "httpbin.org"))
97                          .setPath("/headers")
98                          .build();
99  
100                 System.out.println("Executing request " + request);
101                 final Future<SimpleHttpResponse> future = client.execute(
102                         SimpleRequestProducer.create(request),
103                         SimpleResponseConsumer.create(),
104                         new FutureCallback<SimpleHttpResponse>() {
105 
106                             @Override
107                             public void completed(final SimpleHttpResponse response) {
108                                 System.out.println(request + "->" + new StatusLine(response));
109                                 System.out.println(response.getBody());
110                             }
111 
112                             @Override
113                             public void failed(final Exception ex) {
114                                 System.out.println(request + "->" + ex);
115                             }
116 
117                             @Override
118                             public void cancelled() {
119                                 System.out.println(request + " cancelled");
120                             }
121 
122                         });
123                 future.get();
124             }
125 
126             System.out.println("Shutting down");
127             client.close(CloseMode.GRACEFUL);
128         }
129     }
130 
131 }