0
# Authentication and Session Management
1
2
The Executor class manages authentication credentials, cookies, and connection pooling for multiple HTTP requests. It maintains a shared context that persists across request executions.
3
4
## Executor Creation
5
6
Create Executor instances using static factory methods:
7
8
```java { .api }
9
public static Executor newInstance();
10
public static Executor newInstance(HttpClient httpclient);
11
```
12
13
### Usage Examples
14
15
```java
16
import org.apache.http.client.fluent.Executor;
17
import org.apache.http.impl.client.HttpClients;
18
19
// Default executor with built-in HttpClient
20
Executor executor = Executor.newInstance();
21
22
// Custom executor with your own HttpClient
23
HttpClient customClient = HttpClients.createDefault();
24
Executor customExecutor = Executor.newInstance(customClient);
25
```
26
27
## Authentication Configuration
28
29
Configure various authentication schemes using fluent methods:
30
31
```java { .api }
32
public Executor use(CredentialsProvider credentialsProvider);
33
public Executor auth(AuthScope authScope, Credentials creds);
34
public Executor auth(HttpHost host, Credentials creds);
35
public Executor auth(String host, Credentials creds);
36
public Executor auth(Credentials cred);
37
public Executor auth(String username, String password);
38
public Executor auth(String username, String password, String workstation, String domain);
39
public Executor auth(HttpHost host, String username, String password);
40
public Executor auth(HttpHost host, String username, String password, String workstation, String domain);
41
public Executor clearAuth();
42
```
43
44
### Basic Authentication
45
46
```java
47
import org.apache.http.HttpHost;
48
49
// Global authentication (applies to any host)
50
Executor executor = Executor.newInstance()
51
.auth("username", "password");
52
53
// Host-specific authentication
54
executor = Executor.newInstance()
55
.auth(new HttpHost("api.example.com", 443, "https"), "user", "pass")
56
.auth("api2.example.com:8080", "user2", "pass2");
57
58
// Clear all authentication
59
executor.clearAuth();
60
```
61
62
### NTLM Authentication
63
64
```java
65
// NTLM authentication with domain and workstation
66
Executor executor = Executor.newInstance()
67
.auth("username", "password", "WORKSTATION", "DOMAIN");
68
69
// Host-specific NTLM authentication
70
executor = Executor.newInstance()
71
.auth(new HttpHost("intranet.company.com"), "user", "pass", "WS01", "COMPANY");
72
```
73
74
### Custom Credentials Provider
75
76
```java
77
import org.apache.http.auth.AuthScope;
78
import org.apache.http.auth.UsernamePasswordCredentials;
79
import org.apache.http.impl.client.BasicCredentialsProvider;
80
81
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
82
credentialsProvider.setCredentials(
83
new AuthScope("api.example.com", 443),
84
new UsernamePasswordCredentials("username", "password")
85
);
86
87
Executor executor = Executor.newInstance()
88
.use(credentialsProvider);
89
```
90
91
### Advanced Authentication Scope
92
93
```java
94
import org.apache.http.auth.AuthScope;
95
import org.apache.http.auth.UsernamePasswordCredentials;
96
97
// Authentication for specific host, port, and realm
98
AuthScope scope = new AuthScope("secure.example.com", 443, "admin-realm");
99
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "secret");
100
101
Executor executor = Executor.newInstance()
102
.auth(scope, creds);
103
```
104
105
## Preemptive Authentication
106
107
Enable preemptive authentication to send credentials with the first request:
108
109
```java { .api }
110
public Executor authPreemptive(HttpHost host);
111
public Executor authPreemptive(String host);
112
public Executor authPreemptiveProxy(HttpHost proxy);
113
public Executor authPreemptiveProxy(String proxy);
114
```
115
116
### Usage Examples
117
118
```java
119
// Preemptive authentication for host
120
Executor executor = Executor.newInstance()
121
.auth("api.example.com", "username", "password")
122
.authPreemptive("api.example.com");
123
124
// Preemptive authentication for proxy
125
executor = Executor.newInstance()
126
.auth("proxy.company.com:8080", "proxyuser", "proxypass")
127
.authPreemptiveProxy("proxy.company.com:8080");
128
```
129
130
## Cookie Management
131
132
Manage cookies across multiple requests:
133
134
```java { .api }
135
public Executor use(CookieStore cookieStore);
136
public Executor clearCookies();
137
```
138
139
### Usage Examples
140
141
```java
142
import org.apache.http.client.CookieStore;
143
import org.apache.http.impl.client.BasicCookieStore;
144
145
// Custom cookie store
146
CookieStore cookieStore = new BasicCookieStore();
147
Executor executor = Executor.newInstance()
148
.use(cookieStore);
149
150
// Execute requests that set/use cookies
151
executor.execute(Request.Post("https://example.com/login")
152
.bodyForm(Form.form()
153
.add("username", "user")
154
.add("password", "pass")
155
.build()));
156
157
// Subsequent requests will include session cookies
158
Content response = executor.execute(Request.Get("https://example.com/profile"))
159
.returnContent();
160
161
// Clear all cookies
162
executor.clearCookies();
163
```
164
165
## Request Execution
166
167
Execute requests using the configured executor context:
168
169
```java { .api }
170
public Response execute(Request request) throws ClientProtocolException, IOException;
171
```
172
173
### Usage Examples
174
175
```java
176
import org.apache.http.client.fluent.Request;
177
import org.apache.http.client.fluent.Response;
178
179
Executor executor = Executor.newInstance()
180
.auth("api.example.com", "username", "password");
181
182
// All requests executed through this executor will use the configured authentication
183
Response response1 = executor.execute(Request.Get("https://api.example.com/data"));
184
Response response2 = executor.execute(Request.Post("https://api.example.com/create")
185
.bodyString("{\"name\":\"test\"}", ContentType.APPLICATION_JSON));
186
187
String data1 = response1.returnContent().asString();
188
String data2 = response2.returnContent().asString();
189
```
190
191
## Connection Pool Management
192
193
The Executor uses a shared connection pool with the following configuration:
194
195
- **Maximum connections per route**: 100
196
- **Total maximum connections**: 200
197
- **Connection validation after inactivity**: 1000ms
198
199
```java { .api }
200
public static void closeIdleConnections();
201
```
202
203
### Usage Examples
204
205
```java
206
// Close idle connections to free resources
207
Executor.closeIdleConnections();
208
209
// Typically called during application shutdown
210
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
211
Executor.closeIdleConnections();
212
}));
213
```
214
215
## Deprecated Methods
216
217
```java { .api }
218
@Deprecated public Executor cookieStore(CookieStore cookieStore);
219
@Deprecated public static void registerScheme(org.apache.http.conn.scheme.Scheme scheme);
220
@Deprecated public static void unregisterScheme(String name);
221
```
222
223
Use `use(CookieStore)` instead of `cookieStore()`. The scheme registration methods have no effect.
224
225
## Thread Safety
226
227
The Executor class is **thread-safe** and can be shared across multiple threads:
228
229
```java
230
// Thread-safe: can be used concurrently
231
Executor sharedExecutor = Executor.newInstance()
232
.auth("api.example.com", "username", "password");
233
234
// Multiple threads can use the same executor
235
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
236
try {
237
return sharedExecutor.execute(Request.Get("https://api.example.com/data1"))
238
.returnContent().asString();
239
} catch (IOException e) {
240
throw new RuntimeException(e);
241
}
242
});
243
244
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
245
try {
246
return sharedExecutor.execute(Request.Get("https://api.example.com/data2"))
247
.returnContent().asString();
248
} catch (IOException e) {
249
throw new RuntimeException(e);
250
}
251
});
252
```
253
254
## Complete Example: Authenticated Session
255
256
```java
257
import org.apache.http.client.fluent.*;
258
import java.io.IOException;
259
260
public class AuthenticatedSession {
261
public static void main(String[] args) {
262
try {
263
// Create executor with authentication
264
Executor executor = Executor.newInstance()
265
.auth("api.example.com", "username", "password")
266
.authPreemptive("api.example.com");
267
268
// Login request (sets session cookies)
269
String loginResponse = executor.execute(
270
Request.Post("https://api.example.com/login")
271
.bodyForm(Form.form()
272
.add("username", "user")
273
.add("password", "pass")
274
.build())
275
).returnContent().asString();
276
277
// Subsequent authenticated requests
278
String userData = executor.execute(
279
Request.Get("https://api.example.com/user/profile")
280
).returnContent().asString();
281
282
String updateResponse = executor.execute(
283
Request.Put("https://api.example.com/user/profile")
284
.bodyString("{\"email\":\"new@example.com\"}", ContentType.APPLICATION_JSON)
285
).returnContent().asString();
286
287
System.out.println("Login: " + loginResponse);
288
System.out.println("Profile: " + userData);
289
System.out.println("Update: " + updateResponse);
290
291
} catch (IOException e) {
292
System.err.println("Request failed: " + e.getMessage());
293
} finally {
294
// Clean up connections
295
Executor.closeIdleConnections();
296
}
297
}
298
}
299
```