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