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