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  
28  package org.apache.hc.client5.http.examples;
29  
30  import java.net.InetAddress;
31  import java.net.UnknownHostException;
32  import java.nio.charset.CodingErrorAction;
33  import java.nio.charset.StandardCharsets;
34  import java.util.Arrays;
35  import java.util.Collections;
36  
37  import javax.net.ssl.SSLContext;
38  
39  import org.apache.hc.client5.http.ContextBuilder;
40  import org.apache.hc.client5.http.DnsResolver;
41  import org.apache.hc.client5.http.HttpRoute;
42  import org.apache.hc.client5.http.SystemDefaultDnsResolver;
43  import org.apache.hc.client5.http.auth.CredentialsProvider;
44  import org.apache.hc.client5.http.auth.StandardAuthScheme;
45  import org.apache.hc.client5.http.classic.methods.HttpGet;
46  import org.apache.hc.client5.http.config.ConnectionConfig;
47  import org.apache.hc.client5.http.config.RequestConfig;
48  import org.apache.hc.client5.http.config.TlsConfig;
49  import org.apache.hc.client5.http.cookie.BasicCookieStore;
50  import org.apache.hc.client5.http.cookie.CookieStore;
51  import org.apache.hc.client5.http.cookie.StandardCookieSpec;
52  import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
53  import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
54  import org.apache.hc.client5.http.impl.classic.HttpClients;
55  import org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory;
56  import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
57  import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
58  import org.apache.hc.client5.http.io.ManagedHttpClientConnection;
59  import org.apache.hc.client5.http.protocol.HttpClientContext;
60  import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
61  import org.apache.hc.client5.http.ssl.TlsSocketStrategy;
62  import org.apache.hc.core5.http.ClassicHttpRequest;
63  import org.apache.hc.core5.http.ClassicHttpResponse;
64  import org.apache.hc.core5.http.Header;
65  import org.apache.hc.core5.http.HttpHost;
66  import org.apache.hc.core5.http.ParseException;
67  import org.apache.hc.core5.http.config.CharCodingConfig;
68  import org.apache.hc.core5.http.config.Http1Config;
69  import org.apache.hc.core5.http.impl.io.DefaultClassicHttpResponseFactory;
70  import org.apache.hc.core5.http.impl.io.DefaultHttpRequestWriterFactory;
71  import org.apache.hc.core5.http.impl.io.DefaultHttpResponseParser;
72  import org.apache.hc.core5.http.impl.io.DefaultHttpResponseParserFactory;
73  import org.apache.hc.core5.http.io.HttpConnectionFactory;
74  import org.apache.hc.core5.http.io.HttpMessageParser;
75  import org.apache.hc.core5.http.io.HttpMessageParserFactory;
76  import org.apache.hc.core5.http.io.HttpMessageWriterFactory;
77  import org.apache.hc.core5.http.io.SocketConfig;
78  import org.apache.hc.core5.http.io.entity.EntityUtils;
79  import org.apache.hc.core5.http.message.BasicHeader;
80  import org.apache.hc.core5.http.message.BasicLineParser;
81  import org.apache.hc.core5.http.message.LineParser;
82  import org.apache.hc.core5.http.message.StatusLine;
83  import org.apache.hc.core5.http.ssl.TLS;
84  import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
85  import org.apache.hc.core5.pool.PoolReusePolicy;
86  import org.apache.hc.core5.ssl.SSLContexts;
87  import org.apache.hc.core5.util.CharArrayBuffer;
88  import org.apache.hc.core5.util.TimeValue;
89  import org.apache.hc.core5.util.Timeout;
90  
91  /**
92   * This example demonstrates how to customize and configure the most common aspects
93   * of HTTP request execution and connection management.
94   */
95  public class ClientConfiguration {
96  
97      public final static void main(final String[] args) throws Exception {
98  
99          // Create HTTP/1.1 protocol configuration
100         final Http1Config h1Config = Http1Config.custom()
101                 .setMaxHeaderCount(200)
102                 .setMaxLineLength(2000)
103                 .build();
104 
105         // Use custom message parser / writer to customize the way HTTP
106         // messages are parsed from and written out to the data stream.
107         final HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
108 
109             @Override
110             public HttpMessageParser<ClassicHttpResponse> create() {
111                 final LineParser lineParser = new BasicLineParser() {
112 
113                     @Override
114                     public Header parseHeader(final CharArrayBuffer buffer) {
115                         try {
116                             return super.parseHeader(buffer);
117                         } catch (final ParseException ex) {
118                             return new BasicHeader(buffer.toString(), null);
119                         }
120                     }
121 
122                 };
123                 return new DefaultHttpResponseParser(h1Config, lineParser, DefaultClassicHttpResponseFactory.INSTANCE);
124             }
125 
126         };
127         final HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
128 
129         // Create char coding configuration
130         final CharCodingConfig charCodingConfig = CharCodingConfig.custom()
131                 .setMalformedInputAction(CodingErrorAction.IGNORE)
132                 .setUnmappableInputAction(CodingErrorAction.IGNORE)
133                 .setCharset(StandardCharsets.UTF_8)
134                 .build();
135 
136         // Use a custom connection factory to customize the process of
137         // initialization of outgoing HTTP connections. Beside standard connection
138         // configuration parameters HTTP connection factory can define message
139         // parser / writer routines to be employed by individual connections.
140         final HttpConnectionFactory<ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
141                 h1Config, charCodingConfig, requestWriterFactory, responseParserFactory);
142 
143         // Client HTTP connection objects when fully initialized can be bound to
144         // an arbitrary network socket. The process of network socket initialization,
145         // its connection to a remote address and binding to a local one is controlled
146         // by a connection socket factory.
147 
148         // SSL context for secure connections can be created either based on
149         // system or application specific properties.
150         final SSLContext sslContext = SSLContexts.createSystemDefault();
151 
152         // Create a registry of custom connection socket factories for supported
153         // protocol schemes.
154         final TlsSocketStrategy tlsStrategy = new DefaultClientTlsStrategy(sslContext);
155 
156         // Use custom DNS resolver to override the system DNS resolution.
157         final DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
158 
159             @Override
160             public InetAddress[] resolve(final String host) throws UnknownHostException {
161                 if (host.equalsIgnoreCase("myhost")) {
162                     return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) };
163                 }
164                 return super.resolve(host);
165             }
166 
167         };
168 
169         // Create a connection manager with custom configuration.
170         final PoolingHttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
171                 .setTlsSocketStrategy(tlsStrategy)
172                 .setConnectionFactory(connFactory)
173                 .setDnsResolver(dnsResolver)
174                 .setPoolConcurrencyPolicy(PoolConcurrencyPolicy.STRICT)
175                 .setConnPoolPolicy(PoolReusePolicy.LIFO)
176                 .build();
177 
178         // Configure the connection manager to use socket configuration either
179         // by default or for a specific host.
180         connManager.setDefaultSocketConfig(SocketConfig.custom()
181                 .setTcpNoDelay(true)
182                 .build());
183         // Validate connections after 10 sec of inactivity
184         connManager.setDefaultConnectionConfig(ConnectionConfig.custom()
185                 .setConnectTimeout(Timeout.ofSeconds(30))
186                 .setSocketTimeout(Timeout.ofSeconds(30))
187                 .setValidateAfterInactivity(TimeValue.ofSeconds(10))
188                 .setTimeToLive(TimeValue.ofHours(1))
189                 .build());
190 
191         // Use TLS v1.3 only
192         connManager.setDefaultTlsConfig(TlsConfig.custom()
193                 .setHandshakeTimeout(Timeout.ofSeconds(30))
194                 .setSupportedProtocols(TLS.V_1_3)
195                 .build());
196 
197         // Configure total max or per route limits for persistent connections
198         // that can be kept in the pool or leased by the connection manager.
199         connManager.setMaxTotal(100);
200         connManager.setDefaultMaxPerRoute(10);
201         connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);
202 
203         // Use custom cookie store if necessary.
204         final CookieStore cookieStore = new BasicCookieStore();
205         // Use custom credentials provider if necessary.
206         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
207                 .build();
208         // Create global request configuration
209         final RequestConfig defaultRequestConfig = RequestConfig.custom()
210             .setCookieSpec(StandardCookieSpec.STRICT)
211             .setExpectContinueEnabled(true)
212             .setTargetPreferredAuthSchemes(Arrays.asList(StandardAuthScheme.DIGEST))
213             .setProxyPreferredAuthSchemes(Collections.singletonList(StandardAuthScheme.BASIC))
214             .build();
215 
216         // Create an HttpClient with the given custom dependencies and configuration.
217 
218         try (final CloseableHttpClient httpclient = HttpClients.custom()
219                 .setConnectionManager(connManager)
220                 .setDefaultCookieStore(cookieStore)
221                 .setDefaultCredentialsProvider(credentialsProvider)
222                 .setProxy(new HttpHost("myproxy", 8080))
223                 .setDefaultRequestConfig(defaultRequestConfig)
224                 .build()) {
225             final HttpGet httpget = new HttpGet("http://httpbin.org/get");
226             // Request configuration can be overridden at the request level.
227             // They will take precedence over the one set at the client level.
228             final RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
229                     .setConnectionRequestTimeout(Timeout.ofSeconds(5))
230                     .build();
231             httpget.setConfig(requestConfig);
232 
233             // Execution context can be customized locally.
234             // Contextual attributes set the local context level will take
235             // precedence over those set at the client level.
236             final HttpClientContext context = ContextBuilder.create()
237                     .useCookieStore(cookieStore)
238                     .useCredentialsProvider(credentialsProvider)
239                     .build();
240 
241             System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
242             httpclient.execute(httpget, context, response -> {
243                 System.out.println("----------------------------------------");
244                 System.out.println(httpget + "->" + new StatusLine(response));
245                 EntityUtils.consume(response.getEntity());
246                 return null;
247             });
248             // Last executed request
249             context.getRequest();
250             // Execution route
251             context.getHttpRoute();
252             // Auth exchanges
253             context.getAuthExchanges();
254             // Cookie origin
255             context.getCookieOrigin();
256             // Cookie spec used
257             context.getCookieSpec();
258             // User security token
259             context.getUserToken();
260         }
261     }
262 
263 }
264