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.SSLConnectionSocketFactory;
61  import org.apache.hc.core5.http.ClassicHttpRequest;
62  import org.apache.hc.core5.http.ClassicHttpResponse;
63  import org.apache.hc.core5.http.Header;
64  import org.apache.hc.core5.http.HttpHost;
65  import org.apache.hc.core5.http.ParseException;
66  import org.apache.hc.core5.http.config.CharCodingConfig;
67  import org.apache.hc.core5.http.config.Http1Config;
68  import org.apache.hc.core5.http.impl.io.DefaultClassicHttpResponseFactory;
69  import org.apache.hc.core5.http.impl.io.DefaultHttpRequestWriterFactory;
70  import org.apache.hc.core5.http.impl.io.DefaultHttpResponseParser;
71  import org.apache.hc.core5.http.impl.io.DefaultHttpResponseParserFactory;
72  import org.apache.hc.core5.http.io.HttpConnectionFactory;
73  import org.apache.hc.core5.http.io.HttpMessageParser;
74  import org.apache.hc.core5.http.io.HttpMessageParserFactory;
75  import org.apache.hc.core5.http.io.HttpMessageWriterFactory;
76  import org.apache.hc.core5.http.io.SocketConfig;
77  import org.apache.hc.core5.http.io.entity.EntityUtils;
78  import org.apache.hc.core5.http.message.BasicHeader;
79  import org.apache.hc.core5.http.message.BasicLineParser;
80  import org.apache.hc.core5.http.message.LineParser;
81  import org.apache.hc.core5.http.message.StatusLine;
82  import org.apache.hc.core5.http.ssl.TLS;
83  import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
84  import org.apache.hc.core5.pool.PoolReusePolicy;
85  import org.apache.hc.core5.ssl.SSLContexts;
86  import org.apache.hc.core5.util.CharArrayBuffer;
87  import org.apache.hc.core5.util.TimeValue;
88  import org.apache.hc.core5.util.Timeout;
89  
90  /**
91   * This example demonstrates how to customize and configure the most common aspects
92   * of HTTP request execution and connection management.
93   */
94  public class ClientConfiguration {
95  
96      public final static void main(final String[] args) throws Exception {
97  
98          // Create HTTP/1.1 protocol configuration
99          final Http1Config h1Config = Http1Config.custom()
100                 .setMaxHeaderCount(200)
101                 .setMaxLineLength(2000)
102                 .build();
103 
104         // Use custom message parser / writer to customize the way HTTP
105         // messages are parsed from and written out to the data stream.
106         final HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
107 
108             @Override
109             public HttpMessageParser<ClassicHttpResponse> create() {
110                 final LineParser lineParser = new BasicLineParser() {
111 
112                     @Override
113                     public Header parseHeader(final CharArrayBuffer buffer) {
114                         try {
115                             return super.parseHeader(buffer);
116                         } catch (final ParseException ex) {
117                             return new BasicHeader(buffer.toString(), null);
118                         }
119                     }
120 
121                 };
122                 return new DefaultHttpResponseParser(h1Config, lineParser, DefaultClassicHttpResponseFactory.INSTANCE);
123             }
124 
125         };
126         final HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
127 
128         // Create connection configuration
129         final CharCodingConfig connectionConfig = CharCodingConfig.custom()
130                 .setMalformedInputAction(CodingErrorAction.IGNORE)
131                 .setUnmappableInputAction(CodingErrorAction.IGNORE)
132                 .setCharset(StandardCharsets.UTF_8)
133                 .build();
134 
135         // Use a custom connection factory to customize the process of
136         // initialization of outgoing HTTP connections. Beside standard connection
137         // configuration parameters HTTP connection factory can define message
138         // parser / writer routines to be employed by individual connections.
139         final HttpConnectionFactory<ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
140                 h1Config, connectionConfig, requestWriterFactory, responseParserFactory);
141 
142         // Client HTTP connection objects when fully initialized can be bound to
143         // an arbitrary network socket. The process of network socket initialization,
144         // its connection to a remote address and binding to a local one is controlled
145         // by a connection socket factory.
146 
147         // SSL context for secure connections can be created either based on
148         // system or application specific properties.
149         final SSLContext sslContext = SSLContexts.createSystemDefault();
150 
151         // Create a registry of custom connection socket factories for supported
152         // protocol schemes.
153         final SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
154 
155         // Use custom DNS resolver to override the system DNS resolution.
156         final DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
157 
158             @Override
159             public InetAddress[] resolve(final String host) throws UnknownHostException {
160                 if (host.equalsIgnoreCase("myhost")) {
161                     return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) };
162                 } else {
163                     return super.resolve(host);
164                 }
165             }
166 
167         };
168 
169         // Create a connection manager with custom configuration.
170         final PoolingHttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
171                 .setSSLSocketFactory(sslConnectionSocketFactory)
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