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