0
# Apache HTTP Client
1
2
AWS Java SDK HTTP client implementation using Apache HttpComponents for robust HTTP communication with AWS services. This library provides a full-featured synchronous HTTP client with support for connection pooling, SSL/TLS configuration, proxy authentication, and comprehensive metrics collection.
3
4
**Note**: This module is part of the AWS SDK for Java v2. It provides the Apache HttpComponents-based HTTP client implementation. For other AWS services, authentication, regions management, and the complete SDK functionality, you'll need additional AWS SDK modules. This documentation covers only the HTTP client transport layer.
5
6
## Package Information
7
8
- **Package Name**: apache-client
9
- **Package Type**: maven
10
- **Group ID**: software.amazon.awssdk
11
- **Module Name**: software.amazon.awssdk.http.apache
12
- **Language**: Java
13
- **Installation**:
14
```xml
15
<dependency>
16
<groupId>software.amazon.awssdk</groupId>
17
<artifactId>apache-client</artifactId>
18
<version>2.32.31</version>
19
</dependency>
20
```
21
22
## Core Imports
23
24
```java
25
import software.amazon.awssdk.http.apache.ApacheHttpClient;
26
import software.amazon.awssdk.http.apache.ProxyConfiguration;
27
import software.amazon.awssdk.http.SdkHttpClient;
28
```
29
30
## Basic Usage
31
32
```java
33
import software.amazon.awssdk.http.apache.ApacheHttpClient;
34
import software.amazon.awssdk.http.SdkHttpClient;
35
import java.time.Duration;
36
37
// Create client with default configuration
38
SdkHttpClient httpClient = ApacheHttpClient.create();
39
40
// Create client with custom configuration
41
SdkHttpClient customClient = ApacheHttpClient.builder()
42
.socketTimeout(Duration.ofSeconds(30))
43
.connectionTimeout(Duration.ofSeconds(10))
44
.maxConnections(100)
45
.build();
46
47
// Use with AWS SDK services (requires additional AWS SDK service modules)
48
// Example: aws-sdk-java-s3 module for S3Client
49
S3Client s3Client = S3Client.builder()
50
.httpClient(customClient)
51
.build();
52
53
// Always close the client when done
54
customClient.close();
55
```
56
57
## Relationship to AWS SDK for Java v2
58
59
This `apache-client` module is one of several HTTP client implementations available in the AWS SDK for Java v2 ecosystem:
60
61
- **aws-sdk-java** (BOM): Bill of Materials for managing all AWS SDK module versions
62
- **sdk-core**: Core SDK functionality (request/response handling, signing, etc.)
63
- **regions**: AWS regions and endpoints
64
- **auth**: Authentication providers and credential chains
65
- **http-client-spi**: HTTP client service provider interface
66
- **apache-client**: This module - Apache HttpComponents HTTP client implementation
67
- **netty-nio-client**: Async HTTP client using Netty (alternative to this module)
68
- **url-connection-client**: Lightweight HTTP client using JDK URLConnection
69
- **s3**, **dynamodb**, **ec2**, etc.: Individual AWS service clients (300+ available)
70
71
To use AWS services, you typically need:
72
1. This HTTP client module (or an alternative)
73
2. The specific AWS service client modules (e.g., `s3`, `dynamodb`)
74
3. Core SDK modules (automatically included as dependencies)
75
76
## Architecture
77
78
The Apache HTTP client is built around several key components:
79
80
- **ApacheHttpClient**: Main client implementation that wraps Apache HttpComponents
81
- **Builder Pattern**: Fluent configuration interface for all client settings
82
- **Connection Management**: Automatic connection pooling and lifecycle management
83
- **Proxy Support**: Comprehensive HTTP/HTTPS proxy configuration with authentication
84
- **Metrics Integration**: Built-in metrics collection for monitoring and observability
85
- **Service Discovery**: Automatic registration via Java Service Loader mechanism
86
87
## Capabilities
88
89
### HTTP Client Creation
90
91
Create and configure Apache HTTP client instances with various settings.
92
93
```java { .api }
94
public static ApacheHttpClient.Builder builder()
95
public static SdkHttpClient create()
96
public static final String CLIENT_NAME = "Apache"
97
```
98
99
### Client Configuration
100
101
The `ApacheHttpClient.Builder` interface provides comprehensive configuration options:
102
103
```java { .api }
104
public interface Builder extends SdkHttpClient.Builder<ApacheHttpClient.Builder> {
105
Builder socketTimeout(Duration socketTimeout);
106
Builder connectionTimeout(Duration connectionTimeout);
107
Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout);
108
Builder maxConnections(Integer maxConnections);
109
Builder proxyConfiguration(ProxyConfiguration proxyConfiguration);
110
Builder localAddress(InetAddress localAddress);
111
Builder expectContinueEnabled(Boolean expectContinueEnabled);
112
Builder connectionTimeToLive(Duration connectionTimeToLive);
113
Builder connectionMaxIdleTime(Duration maxIdleConnectionTimeout);
114
Builder useIdleConnectionReaper(Boolean useConnectionReaper);
115
Builder dnsResolver(DnsResolver dnsResolver);
116
Builder socketFactory(ConnectionSocketFactory socketFactory);
117
Builder httpRoutePlanner(HttpRoutePlanner proxyConfiguration);
118
Builder credentialsProvider(CredentialsProvider credentialsProvider);
119
Builder tcpKeepAlive(Boolean keepConnectionAlive);
120
Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider);
121
Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider);
122
Builder authSchemeProviderRegistry(Registry<AuthSchemeProvider> authSchemeProviderRegistry);
123
}
124
```
125
126
**Usage Example:**
127
128
```java
129
SdkHttpClient client = ApacheHttpClient.builder()
130
.socketTimeout(Duration.ofSeconds(60))
131
.connectionTimeout(Duration.ofSeconds(10))
132
.connectionAcquisitionTimeout(Duration.ofSeconds(5))
133
.maxConnections(200)
134
.connectionTimeToLive(Duration.ofMinutes(5))
135
.connectionMaxIdleTime(Duration.ofMinutes(1))
136
.useIdleConnectionReaper(true)
137
.tcpKeepAlive(true)
138
.build();
139
```
140
141
### HTTP Request Execution
142
143
Execute HTTP requests with metrics collection and resource management.
144
145
```java { .api }
146
public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request)
147
public void close()
148
public String clientName()
149
```
150
151
**Usage Example:**
152
153
```java
154
// Prepare and execute request
155
ExecutableHttpRequest executableRequest = client.prepareRequest(httpRequest);
156
try {
157
HttpExecuteResponse response = executableRequest.call();
158
// Process response
159
} catch (IOException e) {
160
// Handle execution error
161
} finally {
162
// Request cleanup is automatic
163
}
164
```
165
166
### Proxy Configuration
167
168
Configure HTTP and HTTPS proxy settings with authentication support.
169
170
```java { .api }
171
public final class ProxyConfiguration {
172
public static ProxyConfiguration.Builder builder()
173
174
public String host()
175
public int port()
176
public String scheme()
177
public String username()
178
public String password()
179
public String ntlmDomain()
180
public String ntlmWorkstation()
181
public Set<String> nonProxyHosts()
182
public Boolean preemptiveBasicAuthenticationEnabled()
183
public String resolveScheme()
184
public ProxyConfiguration.Builder toBuilder()
185
}
186
```
187
188
```java { .api }
189
public interface Builder extends CopyableBuilder<Builder, ProxyConfiguration> {
190
Builder endpoint(URI endpoint);
191
Builder username(String username);
192
Builder password(String password);
193
Builder ntlmDomain(String proxyDomain);
194
Builder ntlmWorkstation(String proxyWorkstation);
195
Builder nonProxyHosts(Set<String> nonProxyHosts);
196
Builder addNonProxyHost(String nonProxyHost);
197
Builder preemptiveBasicAuthenticationEnabled(Boolean preemptiveBasicAuthenticationEnabled);
198
Builder useSystemPropertyValues(Boolean useSystemPropertyValues);
199
Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues);
200
Builder scheme(String scheme);
201
}
202
```
203
204
**Usage Examples:**
205
206
```java
207
// Basic proxy configuration
208
ProxyConfiguration basicProxy = ProxyConfiguration.builder()
209
.endpoint(URI.create("http://proxy.example.com:8080"))
210
.build();
211
212
// Authenticated proxy with credentials
213
ProxyConfiguration authProxy = ProxyConfiguration.builder()
214
.endpoint(URI.create("https://secure-proxy.example.com:3128"))
215
.username("proxyuser")
216
.password("proxypass")
217
.preemptiveBasicAuthenticationEnabled(true)
218
.build();
219
220
// NTLM proxy for Windows environments
221
ProxyConfiguration ntlmProxy = ProxyConfiguration.builder()
222
.endpoint(URI.create("http://corporate-proxy.internal:8080"))
223
.username("domain\\username")
224
.password("password")
225
.ntlmDomain("CORPORATE")
226
.ntlmWorkstation("WORKSTATION01")
227
.build();
228
229
// Proxy with non-proxy hosts
230
ProxyConfiguration selectiveProxy = ProxyConfiguration.builder()
231
.endpoint(URI.create("http://proxy.example.com:8080"))
232
.addNonProxyHost("localhost")
233
.addNonProxyHost("*.internal.com")
234
.addNonProxyHost("192.168.*")
235
.build();
236
237
// Use proxy configuration with client
238
SdkHttpClient client = ApacheHttpClient.builder()
239
.proxyConfiguration(authProxy)
240
.build();
241
```
242
243
### Service Registration
244
245
Automatic service discovery for AWS SDK integration.
246
247
```java { .api }
248
public class ApacheSdkHttpService implements SdkHttpService {
249
public SdkHttpClient.Builder createHttpClientBuilder()
250
}
251
```
252
253
The service is automatically registered via the Java Service Loader mechanism in `META-INF/services/software.amazon.awssdk.http.SdkHttpService`.
254
255
## Types
256
257
### Core Types
258
259
```java { .api }
260
// From AWS SDK Core
261
public interface SdkHttpClient extends Closeable {
262
ExecutableHttpRequest prepareRequest(HttpExecuteRequest request);
263
String clientName();
264
void close();
265
}
266
267
public interface ExecutableHttpRequest {
268
HttpExecuteResponse call() throws IOException;
269
void abort();
270
}
271
```
272
273
### Configuration Types
274
275
```java { .api }
276
// From Apache HttpComponents
277
import org.apache.http.conn.DnsResolver;
278
import org.apache.http.conn.socket.ConnectionSocketFactory;
279
import org.apache.http.conn.routing.HttpRoutePlanner;
280
import org.apache.http.client.CredentialsProvider;
281
import org.apache.http.config.Registry;
282
import org.apache.http.auth.AuthSchemeProvider;
283
284
// From AWS SDK
285
import software.amazon.awssdk.http.TlsKeyManagersProvider;
286
import software.amazon.awssdk.http.TlsTrustManagersProvider;
287
```
288
289
## Error Handling
290
291
The Apache HTTP client can throw various exceptions during operation:
292
293
- **IOException**: Network connectivity issues, timeouts, or server errors
294
- **IllegalArgumentException**: Invalid configuration parameters (e.g., conflicting proxy and route planner settings)
295
- **SSLInitializationException**: SSL context setup failures
296
- **RuntimeException**: Unexpected errors during client operation
297
298
**Common Error Handling Pattern:**
299
300
```java
301
SdkHttpClient client = ApacheHttpClient.builder()
302
.socketTimeout(Duration.ofSeconds(30))
303
.build();
304
305
try {
306
ExecutableHttpRequest request = client.prepareRequest(httpRequest);
307
HttpExecuteResponse response = request.call();
308
// Process successful response
309
} catch (IOException e) {
310
// Handle network/timeout errors
311
log.error("HTTP request failed", e);
312
} finally {
313
client.close();
314
}
315
```
316
317
## Complete AWS SDK Integration Example
318
319
```java
320
// Complete example showing integration with AWS services
321
import software.amazon.awssdk.services.s3.S3Client;
322
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
323
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
324
import software.amazon.awssdk.http.apache.ApacheHttpClient;
325
import software.amazon.awssdk.http.apache.ProxyConfiguration;
326
import software.amazon.awssdk.regions.Region;
327
import software.amazon.awssdk.http.SdkHttpClient;
328
import java.net.URI;
329
import java.time.Duration;
330
331
// 1. Configure the Apache HTTP client
332
SdkHttpClient httpClient = ApacheHttpClient.builder()
333
.socketTimeout(Duration.ofSeconds(30))
334
.connectionTimeout(Duration.ofSeconds(10))
335
.maxConnections(50)
336
.proxyConfiguration(ProxyConfiguration.builder()
337
.endpoint(URI.create("http://proxy.example.com:8080"))
338
.build())
339
.build();
340
341
// 2. Create AWS service client using the HTTP client
342
S3Client s3Client = S3Client.builder()
343
.region(Region.US_EAST_1)
344
.httpClient(httpClient)
345
.build();
346
347
try {
348
// 3. Use the service client
349
ListBucketsResponse response = s3Client.listBuckets(ListBucketsRequest.builder().build());
350
response.buckets().forEach(bucket ->
351
System.out.println("Bucket: " + bucket.name()));
352
} finally {
353
// 4. Clean up resources
354
s3Client.close();
355
httpClient.close();
356
}
357
```
358
359
This example demonstrates:
360
- Configuring the Apache HTTP client with custom settings
361
- Using the HTTP client with an AWS service (S3)
362
- Proper resource management and cleanup
363
364
**Required Dependencies:**
365
```xml
366
<dependencies>
367
<!-- HTTP Client Implementation -->
368
<dependency>
369
<groupId>software.amazon.awssdk</groupId>
370
<artifactId>apache-client</artifactId>
371
<version>2.32.31</version>
372
</dependency>
373
374
<!-- AWS Service Client (example: S3) -->
375
<dependency>
376
<groupId>software.amazon.awssdk</groupId>
377
<artifactId>s3</artifactId>
378
<version>2.32.31</version>
379
</dependency>
380
</dependencies>
381
```
382
383
## Advanced Configuration
384
385
### Custom SSL Configuration
386
387
```java
388
// Custom trust managers for SSL
389
TlsTrustManagersProvider customTrustProvider = () -> {
390
// Return custom trust managers
391
return new TrustManager[] { /* custom managers */ };
392
};
393
394
SdkHttpClient client = ApacheHttpClient.builder()
395
.tlsTrustManagersProvider(customTrustProvider)
396
.build();
397
```
398
399
### Connection Pool Tuning
400
401
```java
402
// High-throughput configuration
403
SdkHttpClient client = ApacheHttpClient.builder()
404
.maxConnections(500)
405
.connectionTimeToLive(Duration.ofMinutes(10))
406
.connectionMaxIdleTime(Duration.ofMinutes(2))
407
.useIdleConnectionReaper(true)
408
.tcpKeepAlive(true)
409
.build();
410
```
411
412
### Custom DNS Resolution
413
414
```java
415
import org.apache.http.conn.DnsResolver;
416
417
DnsResolver customResolver = hostname -> {
418
// Custom DNS resolution logic
419
return new InetAddress[] { /* resolved addresses */ };
420
};
421
422
SdkHttpClient client = ApacheHttpClient.builder()
423
.dnsResolver(customResolver)
424
.build();
425
```