0
# Jersey Client
1
2
Jersey Client is the core client implementation for Jersey, Eclipse's production-quality JAX-RS Reference Implementation for building RESTful web service clients. It provides comprehensive client-side features including request/response processing, entity serialization/deserialization, connector abstractions for different HTTP client implementations, request and response filters for cross-cutting concerns like authentication and logging, async and reactive programming support, and extensive configuration options.
3
4
## Package Information
5
6
- **Package Name**: org.glassfish.jersey.core:jersey-client
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**: Add to Maven dependencies:
10
```xml
11
<dependency>
12
<groupId>org.glassfish.jersey.core</groupId>
13
<artifactId>jersey-client</artifactId>
14
<version>3.1.10</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
import jakarta.ws.rs.client.Client;
22
import jakarta.ws.rs.client.ClientBuilder;
23
import jakarta.ws.rs.client.WebTarget;
24
import jakarta.ws.rs.client.Invocation;
25
import jakarta.ws.rs.core.Response;
26
import org.glassfish.jersey.client.JerseyClientBuilder;
27
import org.glassfish.jersey.client.JerseyClient;
28
```
29
30
## Basic Usage
31
32
```java
33
import jakarta.ws.rs.client.Client;
34
import jakarta.ws.rs.client.WebTarget;
35
import jakarta.ws.rs.core.Response;
36
import org.glassfish.jersey.client.JerseyClientBuilder;
37
38
// Create a client
39
Client client = JerseyClientBuilder.createClient();
40
41
// Create a web target
42
WebTarget target = client.target("https://api.example.com");
43
44
// Execute a GET request
45
Response response = target.path("users")
46
.queryParam("page", 1)
47
.request()
48
.get();
49
50
// Process response
51
if (response.getStatus() == 200) {
52
String json = response.readEntity(String.class);
53
System.out.println(json);
54
}
55
56
// Execute a POST request with entity
57
User user = new User("John", "john@example.com");
58
Response postResponse = target.path("users")
59
.request()
60
.post(Entity.json(user));
61
62
// Clean up
63
client.close();
64
```
65
66
## Architecture
67
68
Jersey Client is built around several key components:
69
70
- **ClientBuilder**: Factory pattern for creating and configuring client instances with SSL, authentication, and connector settings
71
- **Client**: Central coordination point managing resources, configuration, and lifecycle for HTTP operations
72
- **WebTarget**: URI builder providing fluent API for constructing request URIs with path segments, query parameters, and template resolution
73
- **Invocation**: Request executor supporting both synchronous and asynchronous HTTP operations with full JAX-RS compliance
74
- **Connectors**: Pluggable transport layer allowing integration with different HTTP client implementations (HttpUrlConnection, Apache HttpClient, etc.)
75
- **SPI Layer**: Extensibility framework for custom connectors, interceptors, and request/response processing hooks
76
77
This design provides maximum flexibility while maintaining JAX-RS standard compliance, making Jersey Client suitable for enterprise applications, microservices, integration systems, and any Java application requiring robust HTTP client capabilities.
78
79
## Capabilities
80
81
### Client Building and Configuration
82
83
Core client creation and configuration capabilities including SSL context setup, timeout configuration, proxy settings, and connector selection. Essential for establishing HTTP client instances with appropriate security and networking settings.
84
85
```java { .api }
86
// Static factory methods
87
static JerseyClient createClient();
88
static JerseyClient createClient(Configuration configuration);
89
90
// Builder pattern for configuration
91
public class JerseyClientBuilder extends ClientBuilder {
92
public JerseyClient build();
93
public JerseyClientBuilder sslContext(SSLContext sslContext);
94
public JerseyClientBuilder hostnameVerifier(HostnameVerifier hostnameVerifier);
95
public ClientBuilder connectTimeout(long timeout, TimeUnit unit);
96
public ClientBuilder readTimeout(long timeout, TimeUnit unit);
97
public JerseyClientBuilder register(Class<?> componentClass);
98
public JerseyClientBuilder register(Object component);
99
public JerseyClientBuilder property(String name, Object value);
100
}
101
```
102
103
[Client Building and Configuration](./client-config.md)
104
105
### Request Execution
106
107
HTTP request building and execution with support for all standard HTTP methods, custom headers, query parameters, request entities, and both synchronous and asynchronous operations.
108
109
```java { .api }
110
// WebTarget for URI building
111
public class JerseyWebTarget implements WebTarget {
112
JerseyWebTarget path(String path);
113
JerseyWebTarget queryParam(String name, Object... values);
114
JerseyWebTarget matrixParam(String name, Object... values);
115
JerseyInvocation.Builder request();
116
JerseyInvocation.Builder request(String... acceptedResponseTypes);
117
JerseyWebTarget resolveTemplate(String name, Object value);
118
}
119
120
// Request building and execution
121
public static class JerseyInvocation.Builder implements Invocation.Builder {
122
Response get();
123
Response post(Entity<?> entity);
124
Response put(Entity<?> entity);
125
Response delete();
126
<T> T get(Class<T> responseType);
127
<T> T post(Entity<?> entity, Class<T> responseType);
128
Future<Response> submit();
129
<T> Future<T> submit(Class<T> responseType);
130
CompletionStageRxInvoker rx();
131
}
132
```
133
134
[Request Execution](./request-execution.md)
135
136
### Authentication
137
138
HTTP authentication support including Basic authentication, Digest authentication, and Universal authentication modes with both preemptive and non-preemptive options.
139
140
```java { .api }
141
public class HttpAuthenticationFeature implements Feature {
142
static BasicBuilder basicBuilder();
143
static HttpAuthenticationFeature basic(String username, String password);
144
static HttpAuthenticationFeature digest(String username, String password);
145
static UniversalBuilder universalBuilder();
146
static HttpAuthenticationFeature universal(String username, String password);
147
boolean configure(FeatureContext context);
148
}
149
150
// Builder interfaces
151
interface BasicBuilder extends Builder {
152
BasicBuilder nonPreemptive();
153
}
154
155
interface UniversalBuilder extends Builder {
156
UniversalBuilder credentialsForBasic(String username, String password);
157
UniversalBuilder credentialsForDigest(String username, String password);
158
}
159
```
160
161
[Authentication](./authentication.md)
162
163
### Connectors and SPI
164
165
Service Provider Interface for pluggable HTTP transport connectors and extensibility hooks including custom connectors, request/response interceptors, and client lifecycle listeners.
166
167
```java { .api }
168
// Core SPI interfaces
169
public interface ConnectorProvider {
170
Connector getConnector(Client client, Configuration runtimeConfig);
171
}
172
173
public interface Connector extends Inflector<ClientRequest, ClientResponse> {
174
ClientResponse apply(ClientRequest request);
175
Future<?> apply(ClientRequest request, AsyncConnectorCallback callback);
176
String getName();
177
void close();
178
}
179
180
public interface PreInvocationInterceptor {
181
void beforeRequest(ClientRequestContext requestContext);
182
}
183
184
public interface PostInvocationInterceptor {
185
void afterRequest(ClientRequestContext requestContext, ClientResponseContext responseContext);
186
void onException(ClientRequestContext requestContext, ExceptionContext exceptionContext);
187
}
188
```
189
190
[Connectors and SPI](./connectors-spi.md)
191
192
### Filters and Features
193
194
Request/response filters and features for cross-cutting concerns including content encoding, CSRF protection, HTTP Expect: 100-Continue support, and custom filter development.
195
196
```java { .api }
197
// Feature implementations
198
public class EncodingFeature implements Feature {
199
EncodingFeature(String... encodings);
200
EncodingFeature(Class<? extends ContentEncoder>... encoders);
201
boolean configure(FeatureContext context);
202
}
203
204
public class CsrfProtectionFilter implements ClientRequestFilter {
205
CsrfProtectionFilter();
206
CsrfProtectionFilter(String headerName);
207
void filter(ClientRequestContext requestContext);
208
}
209
210
public class Expect100ContinueFeature implements Feature {
211
boolean configure(FeatureContext context);
212
}
213
```
214
215
[Filters and Features](./filters-features.md)
216
217
### Reactive Programming
218
219
Reactive and asynchronous request execution using CompletionStage and custom RxInvoker implementations for non-blocking, composable HTTP operations.
220
221
```java { .api }
222
// CompletionStage-based reactive invocation
223
public class JerseyCompletionStageRxInvoker extends JerseyInvocation.AsyncInvoker implements CompletionStageRxInvoker {
224
// Inherits all HTTP methods from CompletionStageRxInvoker
225
CompletionStage<Response> get();
226
CompletionStage<Response> post(Entity<?> entity);
227
CompletionStage<Response> put(Entity<?> entity);
228
CompletionStage<Response> delete();
229
<T> CompletionStage<T> get(Class<T> responseType);
230
<T> CompletionStage<T> post(Entity<?> entity, Class<T> responseType);
231
<T> CompletionStage<T> put(Entity<?> entity, Class<T> responseType);
232
<T> CompletionStage<T> delete(Class<T> responseType);
233
}
234
235
// Accessing reactive invokers
236
public static class JerseyInvocation.Builder implements Invocation.Builder {
237
CompletionStageRxInvoker rx();
238
<T extends RxInvoker> T rx(Class<T> clazz);
239
}
240
```
241
242
**Usage Examples:**
243
244
```java
245
import java.util.concurrent.CompletionStage;
246
247
// CompletionStage-based reactive requests
248
CompletionStage<Response> asyncResponse = client.target("https://api.example.com")
249
.path("users")
250
.request()
251
.rx()
252
.get();
253
254
// Chain operations with thenApply
255
CompletionStage<User> userStage = client.target("https://api.example.com")
256
.path("users/123")
257
.request()
258
.rx()
259
.get(User.class)
260
.thenApply(user -> {
261
user.setLastAccessed(Instant.now());
262
return user;
263
});
264
265
// Handle errors with exceptionally
266
CompletionStage<String> result = client.target("https://api.example.com")
267
.request()
268
.rx()
269
.get(String.class)
270
.exceptionally(throwable -> "Default response");
271
```
272
273
## Types
274
275
```java { .api }
276
// Core configuration
277
public class ClientConfig implements Configurable<ClientConfig> {
278
ClientConfig();
279
ClientConfig(Class<?>... providerClasses);
280
ClientConfig loadFrom(Configuration config);
281
ClientConfig register(Class<?> providerClass);
282
ClientConfig property(String name, Object value);
283
Object getProperty(String name);
284
ConnectorProvider getConnectorProvider();
285
}
286
287
// Request entity processing modes
288
public enum RequestEntityProcessing {
289
BUFFERED, // Buffer request entity in memory
290
CHUNKED // Stream entity using chunked encoding
291
}
292
293
// Client configuration properties
294
public final class ClientProperties {
295
// Timeout properties
296
public static final String CONNECT_TIMEOUT = "jersey.config.client.connectTimeout";
297
public static final String READ_TIMEOUT = "jersey.config.client.readTimeout";
298
299
// Request processing properties
300
public static final String REQUEST_ENTITY_PROCESSING = "jersey.config.client.request.entity.processing";
301
public static final String CHUNKED_ENCODING_SIZE = "jersey.config.client.chunkedEncodingSize";
302
public static final int DEFAULT_CHUNK_SIZE = 4096;
303
304
// HTTP behavior properties
305
public static final String FOLLOW_REDIRECTS = "jersey.config.client.followRedirects";
306
public static final String SUPPRESS_HTTP_COMPLIANCE_VALIDATION = "jersey.config.client.suppressHttpComplianceValidation";
307
308
// Thread pool properties
309
public static final String ASYNC_THREADPOOL_SIZE = "jersey.config.client.async.threadPoolSize";
310
public static final String BACKGROUND_SCHEDULER_THREADPOOL_SIZE = "jersey.config.client.backgroundScheduler.threadPoolSize";
311
312
// Proxy configuration properties
313
public static final String PROXY_URI = "jersey.config.client.proxy.uri";
314
public static final String PROXY_USERNAME = "jersey.config.client.proxy.username";
315
public static final String PROXY_PASSWORD = "jersey.config.client.proxy.password";
316
317
// Content and encoding properties
318
public static final String USE_ENCODING = "jersey.config.client.useEncoding";
319
public static final String OUTBOUND_CONTENT_LENGTH_BUFFER = "jersey.config.client.outboundContentLengthBuffer";
320
321
// Feature control properties
322
public static final String FEATURE_AUTO_DISCOVERY_DISABLE = "jersey.config.client.feature.autoDiscovery.disable";
323
public static final String JSON_BINDING_FEATURE_DISABLE = "jersey.config.client.json.binding.feature.disable";
324
public static final String JSON_PROCESSING_FEATURE_DISABLE = "jersey.config.client.json.processing.feature.disable";
325
public static final String MOXY_JSON_FEATURE_DISABLE = "jersey.config.client.moxy.json.feature.disable";
326
public static final String METAINF_SERVICES_LOOKUP_DISABLE = "jersey.config.client.metainfServicesLookup.disable";
327
328
// Authentication properties
329
public static final String DIGESTAUTH_URI_CACHE_SIZELIMIT = "jersey.config.client.digestAuthUriCacheSizeLimit";
330
331
// Advanced properties
332
public static final String IGNORE_EXCEPTION_RESPONSE = "jersey.config.client.ignoreExceptionResponse";
333
public static final String EXPECT_100_CONTINUE = "jersey.config.client.request.expect.100.continue.processing";
334
public static final String EXPECT_100_CONTINUE_THRESHOLD_SIZE = "jersey.config.client.request.expect.100.continue.threshold.size";
335
public static final Long DEFAULT_EXPECT_100_CONTINUE_THRESHOLD_SIZE = 65536L;
336
337
// URI and connector properties
338
public static final String QUERY_PARAM_STYLE = "jersey.config.client.uri.query.param.style";
339
public static final String CONNECTOR_PROVIDER = "jersey.config.client.connector.provider";
340
public static final String SNI_HOST_NAME = "jersey.config.client.snihostname";
341
public static final String SSL_CONTEXT_SUPPLIER = "jersey.config.client.ssl.context.supplier";
342
}
343
344
// Streaming support
345
public class ChunkedInput<T> implements Closeable {
346
ChunkedInput(Class<T> chunkType);
347
ChunkedInput(GenericType<T> chunkType);
348
T read() throws IOException;
349
void close() throws IOException;
350
}
351
352
// Exception types
353
public class RequestAuthenticationException extends ProcessingException {
354
RequestAuthenticationException(String message);
355
RequestAuthenticationException(String message, Throwable cause);
356
}
357
358
public class ResponseAuthenticationException extends ResponseProcessingException {
359
ResponseAuthenticationException(Response response, String message);
360
ResponseAuthenticationException(Response response, String message, Throwable cause);
361
}
362
```