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                      } else {
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                  })
78                  .setTlsConfigResolver(host -> {
79                      // Use different settings for specific hosts
80                      if (host.getSchemeName().equalsIgnoreCase("httpbin.org")) {
81                          return TlsConfig.custom()
82                                  .setSupportedProtocols(TLS.V_1_3)
83                                  .setHandshakeTimeout(Timeout.ofSeconds(10))
84                                  .build();
85                      } else {
86                          return TlsConfig.DEFAULT;
87                      }
88                  })
89                  .build();
90          try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
91                  .setConnectionManager(cm)
92                  .build()) {
93  
94              client.start();
95  
96              for (final URIScheme uriScheme : URIScheme.values()) {
97                  final SimpleHttpRequest request = SimpleRequestBuilder.get()
98                          .setHttpHost(new HttpHost(uriScheme.id, "httpbin.org"))
99                          .setPath("/headers")
100                         .build();
101 
102                 System.out.println("Executing request " + request);
103                 final Future<SimpleHttpResponse> future = client.execute(
104                         SimpleRequestProducer.create(request),
105                         SimpleResponseConsumer.create(),
106                         new FutureCallback<SimpleHttpResponse>() {
107 
108                             @Override
109                             public void completed(final SimpleHttpResponse response) {
110                                 System.out.println(request + "->" + new StatusLine(response));
111                                 System.out.println(response.getBody());
112                             }
113 
114                             @Override
115                             public void failed(final Exception ex) {
116                                 System.out.println(request + "->" + ex);
117                             }
118 
119                             @Override
120                             public void cancelled() {
121                                 System.out.println(request + " cancelled");
122                             }
123 
124                         });
125                 future.get();
126             }
127 
128             System.out.println("Shutting down");
129             client.close(CloseMode.GRACEFUL);
130         }
131     }
132 
133 }