0
# HTTP Client
1
2
Spring Boot HTTP client builders for creating Jetty-based HTTP clients. These builders provide an easy way to configure Jetty HTTP clients for use with RestTemplate and WebClient in Spring Boot applications.
3
4
## Capabilities
5
6
### Jetty Client HTTP Request Factory Builder
7
8
Builder for creating JettyClientHttpRequestFactory instances with custom configuration.
9
10
```java { .api }
11
/**
12
* Builder for JettyClientHttpRequestFactory
13
*/
14
public class JettyClientHttpRequestFactoryBuilder
15
implements ClientHttpRequestFactoryBuilder<JettyClientHttpRequestFactory> {
16
17
/** Create builder with default configuration */
18
public JettyClientHttpRequestFactoryBuilder();
19
20
/** Set custom HTTP client instance */
21
public JettyClientHttpRequestFactoryBuilder httpClient(HttpClient httpClient);
22
23
/** Set connect timeout */
24
public JettyClientHttpRequestFactoryBuilder connectTimeout(Duration connectTimeout);
25
26
/** Set read timeout */
27
public JettyClientHttpRequestFactoryBuilder readTimeout(Duration readTimeout);
28
29
/** Build the JettyClientHttpRequestFactory */
30
public JettyClientHttpRequestFactory build();
31
}
32
```
33
34
**Usage Examples:**
35
36
```java
37
@Configuration
38
public class HttpClientConfig {
39
40
@Bean
41
public RestTemplate jettyRestTemplate() {
42
// Create Jetty HTTP client
43
HttpClient httpClient = new HttpClient();
44
httpClient.setConnectTimeout(5000);
45
httpClient.setIdleTimeout(30000);
46
httpClient.setMaxConnectionsPerDestination(20);
47
48
// Create request factory
49
JettyClientHttpRequestFactory requestFactory =
50
new JettyClientHttpRequestFactory(httpClient);
51
requestFactory.setConnectTimeout(Duration.ofSeconds(5));
52
requestFactory.setReadTimeout(Duration.ofSeconds(30));
53
54
// Create RestTemplate
55
RestTemplate restTemplate = new RestTemplate(requestFactory);
56
57
// Add message converters if needed
58
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
59
60
return restTemplate;
61
}
62
63
@Bean
64
public WebClient jettyWebClient() {
65
HttpClient httpClient = new HttpClient();
66
httpClient.setConnectTimeout(5000);
67
httpClient.setFollowRedirects(false);
68
69
JettyClientHttpConnector connector = new JettyClientHttpConnector(httpClient);
70
71
return WebClient.builder()
72
.clientConnector(connector)
73
.defaultHeader(HttpHeaders.USER_AGENT, "My Application")
74
.build();
75
}
76
}
77
```
78
79
### Reactive HTTP Client Connector
80
81
HTTP client connector for reactive applications using Spring WebClient with non-blocking I/O.
82
83
```java { .api }
84
/**
85
* Reactive HTTP client connector using Jetty HTTP client
86
*/
87
public class JettyClientHttpConnector implements ClientHttpConnector {
88
89
/** Create connector with default HTTP client */
90
public JettyClientHttpConnector();
91
92
/** Create connector with custom HTTP client */
93
public JettyClientHttpConnector(HttpClient httpClient);
94
95
/** Create connector with custom resource factory */
96
public JettyClientHttpConnector(JettyResourceFactory resourceFactory);
97
98
/** Connect to the given URI with request */
99
public Mono<ClientHttpResponse> connect(HttpMethod method, URI uri,
100
Function<? super ClientHttpRequest, Mono<Void>> requestCallback);
101
102
/** Get the underlying HTTP client */
103
public HttpClient getHttpClient();
104
}
105
```
106
107
### HTTP Client Configuration
108
109
Comprehensive HTTP client configuration options for connection management and performance tuning.
110
111
```java { .api }
112
/**
113
* HTTP client configuration and customization
114
*/
115
public class HttpClient {
116
117
/** Create HTTP client with default configuration */
118
public HttpClient();
119
120
/** Create HTTP client with SSL context factory */
121
public HttpClient(SslContextFactory.Client sslContextFactory);
122
123
/** Set connect timeout in milliseconds */
124
public void setConnectTimeout(long connectTimeout);
125
126
/** Set idle timeout in milliseconds */
127
public void setIdleTimeout(long idleTimeout);
128
129
/** Set maximum connections per destination */
130
public void setMaxConnectionsPerDestination(int maxConnectionsPerDestination);
131
132
/** Set maximum requests queued per destination */
133
public void setMaxRequestsQueuedPerDestination(int maxRequestsQueuedPerDestination);
134
135
/** Set request buffer size */
136
public void setRequestBufferSize(int requestBufferSize);
137
138
/** Set response buffer size */
139
public void setResponseBufferSize(int responseBufferSize);
140
141
/** Enable/disable HTTP/2 support */
142
public void setHttp2Enabled(boolean http2Enabled);
143
144
/** Set whether to follow redirects */
145
public void setFollowRedirects(boolean followRedirects);
146
147
/** Set user agent string */
148
public void setUserAgentField(HttpField userAgentField);
149
150
/** Add protocol handlers */
151
public void setProtocolHandlers(List<ProtocolHandler> protocolHandlers);
152
153
/** Start the HTTP client */
154
public void start() throws Exception;
155
156
/** Stop the HTTP client */
157
public void stop() throws Exception;
158
}
159
```
160
161
### SSL Configuration for HTTP Client
162
163
SSL/TLS configuration for secure HTTP client connections.
164
165
```java { .api }
166
/**
167
* SSL context factory for Jetty HTTP client
168
*/
169
public class SslContextFactory.Client extends SslContextFactory {
170
171
/** Create SSL context factory for client */
172
public SslContextFactory.Client();
173
174
/** Create SSL context factory with trust all certificates */
175
public SslContextFactory.Client(boolean trustAll);
176
177
/** Set trust store path and password */
178
public void setTrustStorePath(String trustStorePath);
179
public void setTrustStorePassword(String trustStorePassword);
180
181
/** Set key store path and password */
182
public void setKeyStorePath(String keyStorePath);
183
public void setKeyStorePassword(String keyStorePassword);
184
185
/** Set included/excluded protocols */
186
public void setIncludeProtocols(String... protocols);
187
public void setExcludeProtocols(String... protocols);
188
189
/** Set included/excluded cipher suites */
190
public void setIncludeCipherSuites(String... cipherSuites);
191
public void setExcludeCipherSuites(String... cipherSuites);
192
193
/** Enable/disable hostname verification */
194
public void setHostnameVerifier(HostnameVerifier hostnameVerifier);
195
196
/** Set endpoint identification algorithm */
197
public void setEndpointIdentificationAlgorithm(String endpointIdentificationAlgorithm);
198
199
/** Trust all certificates (for testing only) */
200
public void setTrustAll(boolean trustAll);
201
}
202
```
203
204
**SSL Client Configuration Example:**
205
206
```java
207
@Configuration
208
public class SecureHttpClientConfig {
209
210
@Bean
211
public WebClient secureWebClient() {
212
// SSL configuration
213
SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
214
sslContextFactory.setTrustStorePath("/path/to/truststore.jks");
215
sslContextFactory.setTrustStorePassword("truststore-password");
216
sslContextFactory.setIncludeProtocols("TLSv1.2", "TLSv1.3");
217
sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
218
219
// HTTP client configuration
220
HttpClient httpClient = new HttpClient(sslContextFactory);
221
httpClient.setConnectTimeout(10000);
222
httpClient.setIdleTimeout(30000);
223
httpClient.setMaxConnectionsPerDestination(50);
224
225
// Create reactive connector
226
JettyClientHttpConnector connector = new JettyClientHttpConnector(httpClient);
227
228
return WebClient.builder()
229
.clientConnector(connector)
230
.build();
231
}
232
}
233
```
234
235
### Connection Pooling
236
237
Connection pooling configuration for efficient connection reuse and resource management.
238
239
```java { .api }
240
/**
241
* Connection pool configuration for HTTP client
242
*/
243
public class HttpClient {
244
245
/** Set maximum connections per destination */
246
public void setMaxConnectionsPerDestination(int maxConnectionsPerDestination);
247
248
/** Set maximum requests queued per destination */
249
public void setMaxRequestsQueuedPerDestination(int maxRequestsQueuedPerDestination);
250
251
/** Set connection pool timeout */
252
public void setConnectionPoolTimeout(long connectionPoolTimeout);
253
254
/** Set whether to remove idle destinations */
255
public void setRemoveIdleDestinations(boolean removeIdleDestinations);
256
257
/** Get destination statistics */
258
public Set<Destination> getDestinations();
259
260
/** Clear destinations and connections */
261
public void clearDestinations();
262
}
263
```
264
265
### HTTP/2 Support
266
267
HTTP/2 protocol support for improved performance and multiplexing.
268
269
```java { .api }
270
/**
271
* HTTP/2 configuration for Jetty HTTP client
272
*/
273
public class HTTP2Client {
274
275
/** Create HTTP/2 client */
276
public HTTP2Client();
277
278
/** Create HTTP/2 client with connector */
279
public HTTP2Client(Connector connector);
280
281
/** Set initial session receive window */
282
public void setInitialSessionRecvWindow(int initialSessionRecvWindow);
283
284
/** Set initial stream receive window */
285
public void setInitialStreamRecvWindow(int initialStreamRecvWindow);
286
287
/** Set maximum concurrent streams */
288
public void setMaxConcurrentPushedStreams(int maxConcurrentPushedStreams);
289
290
/** Set max frame length */
291
public void setMaxFrameLength(int maxFrameLength);
292
293
/** Connect to HTTP/2 server */
294
public void connect(InetSocketAddress address, Session.Listener listener);
295
296
/** Start the HTTP/2 client */
297
public void start() throws Exception;
298
299
/** Stop the HTTP/2 client */
300
public void stop() throws Exception;
301
}
302
```
303
304
### Request/Response Handling
305
306
Advanced request and response handling with customization options.
307
308
```java { .api }
309
/**
310
* HTTP request and response handling
311
*/
312
public class Request {
313
314
/** Set request timeout */
315
public Request timeout(long timeout, TimeUnit unit);
316
317
/** Set request headers */
318
public Request header(String name, String value);
319
public Request headers(HttpFields headers);
320
321
/** Set request content */
322
public Request content(ContentProvider content);
323
public Request content(ContentProvider content, String contentType);
324
325
/** Set request parameters */
326
public Request param(String name, String value);
327
328
/** Set request attributes */
329
public Request attribute(String name, Object value);
330
331
/** Send request asynchronously */
332
public void send(Response.CompleteListener listener);
333
334
/** Send request synchronously */
335
public ContentResponse send() throws InterruptedException, TimeoutException, ExecutionException;
336
}
337
338
/**
339
* Response handling and processing
340
*/
341
public interface Response {
342
343
/** Get response status */
344
int getStatus();
345
346
/** Get response reason */
347
String getReason();
348
349
/** Get response headers */
350
HttpFields getHeaders();
351
352
/** Get response content */
353
byte[] getContent();
354
355
/** Get response content as string */
356
String getContentAsString();
357
358
/** Get response media type */
359
String getMediaType();
360
361
/** Get response encoding */
362
String getEncoding();
363
}
364
```
365
366
**Advanced Usage Example:**
367
368
```java
369
@Service
370
public class HttpClientService {
371
372
private final HttpClient httpClient;
373
374
public HttpClientService(HttpClient httpClient) {
375
this.httpClient = httpClient;
376
}
377
378
public Mono<String> fetchDataReactively(String url) {
379
Request request = httpClient.newRequest(url)
380
.method(HttpMethod.GET)
381
.timeout(30, TimeUnit.SECONDS)
382
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
383
384
return Mono.fromFuture(request.send().toCompletableFuture())
385
.map(ContentResponse::getContentAsString);
386
}
387
388
public String fetchDataSynchronously(String url) throws Exception {
389
ContentResponse response = httpClient.newRequest(url)
390
.method(HttpMethod.GET)
391
.timeout(30, TimeUnit.SECONDS)
392
.send();
393
394
if (response.getStatus() == 200) {
395
return response.getContentAsString();
396
} else {
397
throw new RuntimeException("HTTP " + response.getStatus() + ": " + response.getReason());
398
}
399
}
400
}
401
```