0
# HTTP Client Management
1
2
HTTP client management provides configurable factories for creating and customizing HTTP clients, supporting both Apache HttpClient and OkHttp. These factories integrate with Spring Cloud's load balancing and service discovery features.
3
4
## Capabilities
5
6
### Apache HTTP Client Factory
7
8
Factory interface for creating and configuring Apache HTTP clients.
9
10
```java { .api }
11
/**
12
* Factory interface for creating Apache HTTP clients
13
*/
14
public interface ApacheHttpClientFactory {
15
/**
16
* Create an HttpClientBuilder with default configuration
17
* @return A configured HttpClientBuilder
18
*/
19
HttpClientBuilder createBuilder();
20
21
/**
22
* Create a CloseableHttpClient with default configuration
23
* @return A configured CloseableHttpClient
24
*/
25
CloseableHttpClient createHttpClient();
26
}
27
```
28
29
### Default Apache HTTP Client Factory
30
31
Default implementation of Apache HTTP client factory.
32
33
```java { .api }
34
/**
35
* Default implementation of Apache HTTP client factory
36
*/
37
public class DefaultApacheHttpClientFactory implements ApacheHttpClientFactory {
38
/**
39
* Create factory with default configuration
40
*/
41
public DefaultApacheHttpClientFactory();
42
43
/**
44
* Create factory with custom connection manager factory
45
* @param connectionManagerFactory The connection manager factory
46
*/
47
public DefaultApacheHttpClientFactory(ApacheHttpClientConnectionManagerFactory connectionManagerFactory);
48
49
@Override
50
public HttpClientBuilder createBuilder() {
51
// Returns configured HttpClientBuilder
52
}
53
54
@Override
55
public CloseableHttpClient createHttpClient() {
56
// Returns configured CloseableHttpClient
57
}
58
}
59
```
60
61
**Usage Examples:**
62
63
```java
64
@Configuration
65
public class HttpClientConfig {
66
67
@Bean
68
public ApacheHttpClientFactory apacheHttpClientFactory() {
69
return new DefaultApacheHttpClientFactory();
70
}
71
72
@Bean
73
public CloseableHttpClient httpClient(ApacheHttpClientFactory factory) {
74
return factory.createHttpClient();
75
}
76
77
@Bean
78
public RestTemplate restTemplate(CloseableHttpClient httpClient) {
79
HttpComponentsClientHttpRequestFactory factory =
80
new HttpComponentsClientHttpRequestFactory(httpClient);
81
return new RestTemplate(factory);
82
}
83
}
84
85
@Service
86
public class HttpService {
87
88
@Autowired
89
private ApacheHttpClientFactory httpClientFactory;
90
91
public void makeCustomRequest() {
92
try (CloseableHttpClient client = httpClientFactory.createHttpClient()) {
93
HttpGet request = new HttpGet("https://api.example.com/data");
94
95
try (CloseableHttpResponse response = client.execute(request)) {
96
// Process response
97
String content = EntityUtils.toString(response.getEntity());
98
System.out.println(content);
99
}
100
} catch (IOException e) {
101
// Handle exception
102
}
103
}
104
}
105
```
106
107
### Apache HTTP Client Connection Manager Factory
108
109
Factory for creating Apache HTTP client connection managers.
110
111
```java { .api }
112
/**
113
* Factory for creating Apache HTTP connection managers
114
*/
115
public interface ApacheHttpClientConnectionManagerFactory {
116
/**
117
* Create a connection manager
118
* @return A configured connection manager
119
*/
120
HttpClientConnectionManager newConnectionManager();
121
122
/**
123
* Create a connection manager with SSL context support
124
* @param disableSslValidation Whether to disable SSL validation
125
* @param maxTotalConnections Maximum total connections
126
* @param maxConnectionsPerRoute Maximum connections per route
127
* @return A configured connection manager
128
*/
129
HttpClientConnectionManager newConnectionManager(boolean disableSslValidation,
130
int maxTotalConnections,
131
int maxConnectionsPerRoute);
132
133
/**
134
* Create a connection manager with custom timeouts
135
* @param disableSslValidation Whether to disable SSL validation
136
* @param maxTotalConnections Maximum total connections
137
* @param maxConnectionsPerRoute Maximum connections per route
138
* @param timeToLive Connection time to live
139
* @param timeUnit Time unit for time to live
140
* @return A configured connection manager
141
*/
142
HttpClientConnectionManager newConnectionManager(boolean disableSslValidation,
143
int maxTotalConnections,
144
int maxConnectionsPerRoute,
145
long timeToLive,
146
TimeUnit timeUnit);
147
148
/**
149
* Create a connection manager with registry and timeouts
150
* @param disableSslValidation Whether to disable SSL validation
151
* @param maxTotalConnections Maximum total connections
152
* @param maxConnectionsPerRoute Maximum connections per route
153
* @param timeToLive Connection time to live
154
* @param timeUnit Time unit for time to live
155
* @param registryBuilder Registry builder for connection socket factories
156
* @return A configured connection manager
157
*/
158
HttpClientConnectionManager newConnectionManager(boolean disableSslValidation,
159
int maxTotalConnections,
160
int maxConnectionsPerRoute,
161
long timeToLive,
162
TimeUnit timeUnit,
163
RegistryBuilder registryBuilder);
164
}
165
```
166
167
### Default Apache Connection Manager Factory
168
169
Default implementation of Apache HTTP client connection manager factory.
170
171
```java { .api }
172
/**
173
* Default implementation of Apache connection manager factory
174
*/
175
public class DefaultApacheHttpClientConnectionManagerFactory
176
implements ApacheHttpClientConnectionManagerFactory {
177
178
/**
179
* Create factory with default configuration
180
*/
181
public DefaultApacheHttpClientConnectionManagerFactory();
182
183
@Override
184
public HttpClientConnectionManager newConnectionManager() {
185
return newConnectionManager(false, 200, 20);
186
}
187
188
@Override
189
public HttpClientConnectionManager newConnectionManager(boolean disableSslValidation,
190
int maxTotalConnections,
191
int maxConnectionsPerRoute) {
192
return newConnectionManager(disableSslValidation, maxTotalConnections,
193
maxConnectionsPerRoute, -1, TimeUnit.MILLISECONDS);
194
}
195
196
// Additional overloaded methods implemented
197
}
198
```
199
200
### OkHttp Client Factory
201
202
Factory interface for creating and configuring OkHttp clients.
203
204
```java { .api }
205
/**
206
* Factory interface for creating OkHttp clients
207
*/
208
public interface OkHttpClientFactory {
209
/**
210
* Create an OkHttpClient.Builder with default configuration
211
* @param disableSslValidation Whether to disable SSL validation
212
* @return A configured OkHttpClient.Builder
213
*/
214
OkHttpClient.Builder createBuilder(boolean disableSslValidation);
215
216
/**
217
* Create an OkHttpClient with default configuration
218
* @return A configured OkHttpClient
219
*/
220
OkHttpClient createHttpClient();
221
}
222
```
223
224
### Default OkHttp Client Factory
225
226
Default implementation of OkHttp client factory.
227
228
```java { .api }
229
/**
230
* Default implementation of OkHttp client factory
231
*/
232
public class DefaultOkHttpClientFactory implements OkHttpClientFactory {
233
/**
234
* Create factory with default configuration
235
*/
236
public DefaultOkHttpClientFactory();
237
238
/**
239
* Create factory with custom connection pool factory
240
* @param connectionPoolFactory The connection pool factory
241
*/
242
public DefaultOkHttpClientFactory(OkHttpClientConnectionPoolFactory connectionPoolFactory);
243
244
@Override
245
public OkHttpClient.Builder createBuilder(boolean disableSslValidation) {
246
// Returns configured OkHttpClient.Builder
247
}
248
249
@Override
250
public OkHttpClient createHttpClient() {
251
// Returns configured OkHttpClient
252
}
253
}
254
```
255
256
**Usage Examples:**
257
258
```java
259
@Configuration
260
public class OkHttpConfig {
261
262
@Bean
263
public OkHttpClientFactory okHttpClientFactory() {
264
return new DefaultOkHttpClientFactory();
265
}
266
267
@Bean
268
public OkHttpClient okHttpClient(OkHttpClientFactory factory) {
269
return factory.createHttpClient();
270
}
271
}
272
273
@Service
274
public class OkHttpService {
275
276
@Autowired
277
private OkHttpClientFactory okHttpClientFactory;
278
279
public void makeRequest() {
280
OkHttpClient client = okHttpClientFactory.createHttpClient();
281
282
Request request = new Request.Builder()
283
.url("https://api.example.com/data")
284
.build();
285
286
try (Response response = client.newCall(request).execute()) {
287
if (response.isSuccessful()) {
288
String content = response.body().string();
289
System.out.println(content);
290
}
291
} catch (IOException e) {
292
// Handle exception
293
}
294
}
295
296
public void makeCustomRequest() {
297
OkHttpClient.Builder builder = okHttpClientFactory.createBuilder(false);
298
299
// Customize the client
300
OkHttpClient client = builder
301
.connectTimeout(30, TimeUnit.SECONDS)
302
.readTimeout(30, TimeUnit.SECONDS)
303
.addInterceptor(new LoggingInterceptor())
304
.build();
305
306
// Use customized client
307
Request request = new Request.Builder()
308
.url("https://api.example.com/data")
309
.build();
310
311
try (Response response = client.newCall(request).execute()) {
312
// Process response
313
} catch (IOException e) {
314
// Handle exception
315
}
316
}
317
}
318
```
319
320
### OkHttp Connection Pool Factory
321
322
Factory for creating OkHttp connection pools.
323
324
```java { .api }
325
/**
326
* Factory for creating OkHttp connection pools
327
*/
328
public interface OkHttpClientConnectionPoolFactory {
329
/**
330
* Create a connection pool
331
* @param maxIdleConnections Maximum idle connections
332
* @param keepAliveDuration Keep alive duration
333
* @param timeUnit Time unit for keep alive duration
334
* @return A configured ConnectionPool
335
*/
336
ConnectionPool create(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit);
337
}
338
```
339
340
### Default OkHttp Connection Pool Factory
341
342
Default implementation of OkHttp connection pool factory.
343
344
```java { .api }
345
/**
346
* Default implementation of OkHttp connection pool factory
347
*/
348
public class DefaultOkHttpClientConnectionPoolFactory implements OkHttpClientConnectionPoolFactory {
349
/**
350
* Create factory with default configuration
351
*/
352
public DefaultOkHttpClientConnectionPoolFactory();
353
354
@Override
355
public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
356
return new ConnectionPool(maxIdleConnections, keepAliveDuration, timeUnit);
357
}
358
}
359
```
360
361
### HTTP Client Configuration
362
363
Auto-configuration for HTTP client factories.
364
365
```java { .api }
366
/**
367
* Auto-configuration for HTTP client factories
368
*/
369
@Configuration
370
@ConditionalOnClass({CloseableHttpClient.class})
371
public class HttpClientConfiguration {
372
373
/**
374
* Apache HTTP client factory configuration
375
*/
376
@Configuration
377
@ConditionalOnProperty(name = "spring.cloud.httpclientfactories.apache.enabled",
378
matchIfMissing = true)
379
protected static class ApacheHttpClientFactoryConfiguration {
380
381
@Bean
382
@ConditionalOnMissingBean
383
public ApacheHttpClientConnectionManagerFactory connectionManagerFactory() {
384
return new DefaultApacheHttpClientConnectionManagerFactory();
385
}
386
387
@Bean
388
@ConditionalOnMissingBean
389
public ApacheHttpClientFactory apacheHttpClientFactory(
390
ApacheHttpClientConnectionManagerFactory connectionManagerFactory) {
391
return new DefaultApacheHttpClientFactory(connectionManagerFactory);
392
}
393
}
394
395
/**
396
* OkHttp client factory configuration
397
*/
398
@Configuration
399
@ConditionalOnClass(OkHttpClient.class)
400
@ConditionalOnProperty(name = "spring.cloud.httpclientfactories.ok.enabled",
401
matchIfMissing = true)
402
protected static class OkHttpClientFactoryConfiguration {
403
404
@Bean
405
@ConditionalOnMissingBean
406
public OkHttpClientConnectionPoolFactory connectionPoolFactory() {
407
return new DefaultOkHttpClientConnectionPoolFactory();
408
}
409
410
@Bean
411
@ConditionalOnMissingBean
412
public OkHttpClientFactory okHttpClientFactory(
413
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
414
return new DefaultOkHttpClientFactory(connectionPoolFactory);
415
}
416
}
417
}
418
```
419
420
## Configuration Properties
421
422
```properties
423
# Apache HTTP client factory
424
spring.cloud.httpclientfactories.apache.enabled=true
425
426
# OkHttp client factory
427
spring.cloud.httpclientfactories.ok.enabled=true
428
429
# Connection pool settings (implementation-specific)
430
spring.cloud.httpclient.connection-pool.max-total=200
431
spring.cloud.httpclient.connection-pool.default-max-per-route=20
432
spring.cloud.httpclient.connection-pool.time-to-live=900
433
spring.cloud.httpclient.connection-pool.time-to-live-unit=seconds
434
435
# SSL settings
436
spring.cloud.httpclient.ssl.trust-store=classpath:truststore.jks
437
spring.cloud.httpclient.ssl.trust-store-password=password
438
spring.cloud.httpclient.ssl.key-store=classpath:keystore.jks
439
spring.cloud.httpclient.ssl.key-store-password=password
440
```
441
442
## Advanced Configuration Examples
443
444
**Custom Apache HTTP Client with SSL:**
445
446
```java
447
@Configuration
448
public class CustomHttpClientConfig {
449
450
@Bean
451
public ApacheHttpClientFactory customApacheHttpClientFactory() {
452
return new ApacheHttpClientFactory() {
453
@Override
454
public HttpClientBuilder createBuilder() {
455
return HttpClients.custom()
456
.setConnectionManager(createCustomConnectionManager())
457
.setDefaultRequestConfig(createRequestConfig())
458
.setRetryHandler(createRetryHandler());
459
}
460
461
@Override
462
public CloseableHttpClient createHttpClient() {
463
return createBuilder().build();
464
}
465
466
private HttpClientConnectionManager createCustomConnectionManager() {
467
try {
468
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
469
sslContextBuilder.loadTrustMaterial(null, (x509Certificates, s) -> true);
470
471
PoolingHttpClientConnectionManager connectionManager =
472
new PoolingHttpClientConnectionManager(
473
RegistryBuilder.<ConnectionSocketFactory>create()
474
.register("http", PlainConnectionSocketFactory.getSocketFactory())
475
.register("https", new SSLConnectionSocketFactory(sslContextBuilder.build()))
476
.build()
477
);
478
479
connectionManager.setMaxTotal(100);
480
connectionManager.setDefaultMaxPerRoute(20);
481
482
return connectionManager;
483
} catch (Exception e) {
484
throw new RuntimeException("Failed to create connection manager", e);
485
}
486
}
487
488
private RequestConfig createRequestConfig() {
489
return RequestConfig.custom()
490
.setConnectTimeout(5000)
491
.setSocketTimeout(10000)
492
.setConnectionRequestTimeout(5000)
493
.build();
494
}
495
496
private HttpRequestRetryHandler createRetryHandler() {
497
return (exception, executionCount, context) -> {
498
if (executionCount >= 3) {
499
return false;
500
}
501
if (exception instanceof InterruptedIOException) {
502
return false;
503
}
504
if (exception instanceof UnknownHostException) {
505
return false;
506
}
507
if (exception instanceof SSLException) {
508
return false;
509
}
510
return true;
511
};
512
}
513
};
514
}
515
}
516
```
517
518
**Custom OkHttp Client with Interceptors:**
519
520
```java
521
@Configuration
522
public class CustomOkHttpConfig {
523
524
@Bean
525
public OkHttpClientFactory customOkHttpClientFactory() {
526
return new OkHttpClientFactory() {
527
@Override
528
public OkHttpClient.Builder createBuilder(boolean disableSslValidation) {
529
OkHttpClient.Builder builder = new OkHttpClient.Builder()
530
.connectTimeout(30, TimeUnit.SECONDS)
531
.readTimeout(30, TimeUnit.SECONDS)
532
.writeTimeout(30, TimeUnit.SECONDS)
533
.connectionPool(new ConnectionPool(50, 5, TimeUnit.MINUTES))
534
.addInterceptor(new LoggingInterceptor())
535
.addInterceptor(new RetryInterceptor());
536
537
if (disableSslValidation) {
538
disableSslVerification(builder);
539
}
540
541
return builder;
542
}
543
544
@Override
545
public OkHttpClient createHttpClient() {
546
return createBuilder(false).build();
547
}
548
549
private void disableSslVerification(OkHttpClient.Builder builder) {
550
try {
551
TrustManager[] trustAllCerts = new TrustManager[]{
552
new X509TrustManager() {
553
@Override
554
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
555
556
@Override
557
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
558
559
@Override
560
public X509Certificate[] getAcceptedIssuers() {
561
return new X509Certificate[]{};
562
}
563
}
564
};
565
566
SSLContext sslContext = SSLContext.getInstance("SSL");
567
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
568
569
builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]);
570
builder.hostnameVerifier((hostname, session) -> true);
571
} catch (Exception e) {
572
throw new RuntimeException("Failed to disable SSL verification", e);
573
}
574
}
575
};
576
}
577
}
578
```