0
# Cookie Management
1
2
HTTP cookie handling with domain scoping, expiration management, security flags, and session persistence. Essential for authentication workflows, session management, and testing cookie-dependent applications.
3
4
## Capabilities
5
6
### CookieManager Class
7
8
Primary interface for HTTP cookie management across web sessions.
9
10
```java { .api }
11
/**
12
* HTTP cookie manager for browser session
13
*/
14
public class CookieManager {
15
/** Create cookie manager with default settings */
16
public CookieManager();
17
18
/** Add cookie to manager */
19
public void addCookie(Cookie cookie);
20
21
/** Get all cookies */
22
public Set<Cookie> getCookies();
23
24
/** Get cookies for specific URL */
25
public Set<Cookie> getCookies(URL url);
26
27
/** Get cookies for specific domain */
28
public Set<Cookie> getCookies(String domain);
29
30
/** Get cookies matching criteria */
31
public Set<Cookie> getCookies(String domain, String path);
32
33
/** Remove specific cookie */
34
public void removeCookie(Cookie cookie);
35
36
/** Remove cookies by name and domain */
37
public void removeCookies(String name, String domain);
38
39
/** Clear all cookies */
40
public void clearCookies();
41
42
/** Clear expired cookies */
43
public void clearExpiredCookies();
44
45
/** Check if cookies are enabled */
46
public boolean isCookiesEnabled();
47
48
/** Enable or disable cookie support */
49
public void setCookiesEnabled(boolean enabled);
50
51
/** Get cookie count */
52
public int getCookieCount();
53
54
/** Check if cookie exists */
55
public boolean hasCookie(String name, String domain);
56
57
/** Get specific cookie */
58
public Cookie getCookie(String name, String domain);
59
60
/** Import cookies from string (Netscape format) */
61
public void importCookies(String cookieData);
62
63
/** Export cookies to string (Netscape format) */
64
public String exportCookies();
65
66
/** Load cookies from file */
67
public void loadCookies(File file) throws IOException;
68
69
/** Save cookies to file */
70
public void saveCookies(File file) throws IOException;
71
}
72
```
73
74
**Usage Examples:**
75
76
```java
77
import com.gargoylesoftware.htmlunit.WebClient;
78
import com.gargoylesoftware.htmlunit.CookieManager;
79
import com.gargoylesoftware.htmlunit.util.Cookie;
80
import java.util.Date;
81
import java.util.Set;
82
83
try (WebClient webClient = new WebClient()) {
84
CookieManager cookieManager = webClient.getCookieManager();
85
86
// Create and add cookies
87
Cookie sessionCookie = new Cookie("example.com", "sessionId", "abc123");
88
cookieManager.addCookie(sessionCookie);
89
90
// Create persistent cookie with expiration
91
Date expiration = new Date(System.currentTimeMillis() + 86400000); // 1 day
92
Cookie persistentCookie = new Cookie("example.com", "userId", "user123", "/", expiration, false, false);
93
cookieManager.addCookie(persistentCookie);
94
95
// Load a page (cookies will be sent automatically)
96
HtmlPage page = webClient.getPage("https://example.com");
97
98
// Check cookies received from server
99
Set<Cookie> allCookies = cookieManager.getCookies();
100
System.out.println("Total cookies: " + allCookies.size());
101
102
for (Cookie cookie : allCookies) {
103
System.out.println("Cookie: " + cookie.getName() + "=" + cookie.getValue() +
104
" (domain: " + cookie.getDomain() + ", path: " + cookie.getPath() + ")");
105
}
106
107
// Get cookies for specific domain
108
Set<Cookie> exampleCookies = cookieManager.getCookies("example.com");
109
System.out.println("Cookies for example.com: " + exampleCookies.size());
110
111
// Check specific cookie
112
if (cookieManager.hasCookie("sessionId", "example.com")) {
113
Cookie cookie = cookieManager.getCookie("sessionId", "example.com");
114
System.out.println("Session ID: " + cookie.getValue());
115
}
116
117
// Clear expired cookies
118
cookieManager.clearExpiredCookies();
119
120
// Save cookies to file for later use
121
cookieManager.saveCookies(new File("cookies.txt"));
122
}
123
```
124
125
### Cookie Class
126
127
Individual HTTP cookie representation with all standard attributes.
128
129
```java { .api }
130
/**
131
* HTTP cookie with standard attributes
132
*/
133
public class Cookie {
134
/** Create basic cookie */
135
public Cookie(String domain, String name, String value);
136
137
/** Create cookie with path */
138
public Cookie(String domain, String name, String value, String path);
139
140
/** Create cookie with expiration */
141
public Cookie(String domain, String name, String value, String path, Date expires);
142
143
/** Create cookie with all attributes */
144
public Cookie(String domain, String name, String value, String path, Date expires, boolean secure, boolean httpOnly);
145
146
/** Create cookie with max age */
147
public Cookie(String domain, String name, String value, String path, int maxAge, boolean secure, boolean httpOnly);
148
149
/** Get cookie name */
150
public String getName();
151
152
/** Get cookie value */
153
public String getValue();
154
155
/** Set cookie value */
156
public void setValue(String value);
157
158
/** Get cookie domain */
159
public String getDomain();
160
161
/** Set cookie domain */
162
public void setDomain(String domain);
163
164
/** Get cookie path */
165
public String getPath();
166
167
/** Set cookie path */
168
public void setPath(String path);
169
170
/** Get expiration date */
171
public Date getExpires();
172
173
/** Set expiration date */
174
public void setExpires(Date expires);
175
176
/** Get max age in seconds */
177
public int getMaxAge();
178
179
/** Set max age in seconds */
180
public void setMaxAge(int maxAge);
181
182
/** Check if cookie is secure (HTTPS only) */
183
public boolean isSecure();
184
185
/** Set secure flag */
186
public void setSecure(boolean secure);
187
188
/** Check if cookie is HTTP only (no JavaScript access) */
189
public boolean isHttpOnly();
190
191
/** Set HTTP only flag */
192
public void setHttpOnly(boolean httpOnly);
193
194
/** Get SameSite attribute */
195
public String getSameSite();
196
197
/** Set SameSite attribute (Strict, Lax, None) */
198
public void setSameSite(String sameSite);
199
200
/** Check if cookie is expired */
201
public boolean isExpired();
202
203
/** Check if cookie is session cookie (no expiration) */
204
public boolean isSessionCookie();
205
206
/** Check if cookie is persistent (has expiration) */
207
public boolean isPersistent();
208
209
/** Get cookie version */
210
public int getVersion();
211
212
/** Set cookie version */
213
public void setVersion(int version);
214
215
/** Get cookie comment */
216
public String getComment();
217
218
/** Set cookie comment */
219
public void setComment(String comment);
220
221
/** Get cookie comment URL */
222
public String getCommentURL();
223
224
/** Set cookie comment URL */
225
public void setCommentURL(String commentURL);
226
227
/** Check if cookie should be discarded */
228
public boolean isToBeDiscarded();
229
230
/** Set discard flag */
231
public void setToBeDiscarded(boolean toBeDiscarded);
232
233
/** Get cookie ports */
234
public int[] getPorts();
235
236
/** Set cookie ports */
237
public void setPorts(int[] ports);
238
239
/** Convert cookie to header string */
240
public String toString();
241
242
/** Convert cookie to Set-Cookie header format */
243
public String toExternalForm();
244
245
/** Check if cookie matches domain and path */
246
public boolean matches(String domain, String path);
247
248
/** Clone the cookie */
249
public Cookie clone();
250
}
251
```
252
253
**Usage Examples:**
254
255
```java
256
import java.util.Calendar;
257
import java.util.Date;
258
259
// Create different types of cookies
260
Cookie sessionCookie = new Cookie("example.com", "JSESSIONID", "1234567890");
261
262
// Persistent cookie with 1 hour expiration
263
Calendar cal = Calendar.getInstance();
264
cal.add(Calendar.HOUR, 1);
265
Cookie persistentCookie = new Cookie("example.com", "rememberMe", "true", "/", cal.getTime(), false, true);
266
267
// Secure cookie for HTTPS
268
Cookie secureCookie = new Cookie("secure.example.com", "authToken", "token123", "/", null, true, true);
269
secureCookie.setSameSite("Strict");
270
271
// Cookie with max age (30 days)
272
Cookie maxAgeCookie = new Cookie("example.com", "preferences", "theme=dark", "/", 30 * 24 * 3600, false, false);
273
274
// Working with cookie attributes
275
System.out.println("Cookie name: " + sessionCookie.getName());
276
System.out.println("Cookie value: " + sessionCookie.getValue());
277
System.out.println("Cookie domain: " + sessionCookie.getDomain());
278
System.out.println("Cookie path: " + sessionCookie.getPath());
279
System.out.println("Is secure: " + sessionCookie.isSecure());
280
System.out.println("Is HTTP only: " + sessionCookie.isHttpOnly());
281
System.out.println("Is session cookie: " + sessionCookie.isSessionCookie());
282
System.out.println("Is expired: " + sessionCookie.isExpired());
283
284
// Modify cookie
285
sessionCookie.setValue("newValue123");
286
sessionCookie.setSecure(true);
287
sessionCookie.setHttpOnly(true);
288
289
// Check if cookie matches domain/path
290
boolean matches = sessionCookie.matches("example.com", "/");
291
System.out.println("Cookie matches example.com/: " + matches);
292
293
// Convert to header format
294
String headerValue = sessionCookie.toExternalForm();
295
System.out.println("Set-Cookie header: " + headerValue);
296
```
297
298
### Cookie Storage and Persistence
299
300
```java { .api }
301
/**
302
* Cookie storage interface for custom implementations
303
*/
304
public interface CookieStore {
305
/** Add cookie to store */
306
void addCookie(Cookie cookie);
307
308
/** Get all cookies from store */
309
List<Cookie> getCookies();
310
311
/** Clear all cookies */
312
boolean clearExpired(Date date);
313
314
/** Clear all cookies */
315
void clear();
316
}
317
318
/**
319
* Basic in-memory cookie store
320
*/
321
public class BasicCookieStore implements CookieStore {
322
/** Create empty cookie store */
323
public BasicCookieStore();
324
325
/** Add cookie */
326
public void addCookie(Cookie cookie);
327
328
/** Get all cookies */
329
public List<Cookie> getCookies();
330
331
/** Clear expired cookies */
332
public boolean clearExpired(Date date);
333
334
/** Clear all cookies */
335
public void clear();
336
337
/** Get cookie count */
338
public int size();
339
}
340
```
341
342
### Cookie Filtering and Matching
343
344
```java { .api }
345
/**
346
* Cookie specification for parsing and matching
347
*/
348
public interface CookieSpec {
349
/** Parse Set-Cookie header */
350
List<Cookie> parse(Header header, CookieOrigin origin) throws MalformedCookieException;
351
352
/** Validate cookie */
353
void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException;
354
355
/** Check if cookie matches origin */
356
boolean match(Cookie cookie, CookieOrigin origin);
357
358
/** Format cookies for Cookie header */
359
List<Header> formatCookies(List<Cookie> cookies);
360
361
/** Get version handled by this spec */
362
int getVersion();
363
364
/** Get version header */
365
Header getVersionHeader();
366
}
367
368
/**
369
* Cookie origin for domain/path matching
370
*/
371
public class CookieOrigin {
372
/** Create cookie origin */
373
public CookieOrigin(String host, int port, String path, boolean secure);
374
375
/** Get host */
376
public String getHost();
377
378
/** Get port */
379
public int getPort();
380
381
/** Get path */
382
public String getPath();
383
384
/** Check if secure */
385
public boolean isSecure();
386
}
387
```
388
389
### Advanced Cookie Management
390
391
**Cookie Filtering:**
392
393
```java
394
// Filter cookies by criteria
395
CookieManager cookieManager = webClient.getCookieManager();
396
397
// Get only secure cookies
398
Set<Cookie> secureCookies = cookieManager.getCookies().stream()
399
.filter(Cookie::isSecure)
400
.collect(Collectors.toSet());
401
402
// Get only session cookies
403
Set<Cookie> sessionCookies = cookieManager.getCookies().stream()
404
.filter(Cookie::isSessionCookie)
405
.collect(Collectors.toSet());
406
407
// Get cookies for subdomain
408
Set<Cookie> subdomainCookies = cookieManager.getCookies().stream()
409
.filter(cookie -> cookie.getDomain().endsWith(".example.com"))
410
.collect(Collectors.toSet());
411
412
// Remove expired cookies
413
cookieManager.getCookies().stream()
414
.filter(Cookie::isExpired)
415
.forEach(cookieManager::removeCookie);
416
```
417
418
**Cookie Import/Export:**
419
420
```java
421
// Export cookies to Netscape format
422
String cookieData = cookieManager.exportCookies();
423
System.out.println("Exported cookies:\n" + cookieData);
424
425
// Save to file
426
try (FileWriter writer = new FileWriter("cookies.txt")) {
427
writer.write(cookieData);
428
}
429
430
// Import cookies from string
431
String importData = """
432
# Netscape HTTP Cookie File
433
.example.com TRUE / FALSE 1609459200 sessionId abc123
434
.example.com TRUE /admin TRUE 1609459200 adminToken xyz789
435
""";
436
cookieManager.importCookies(importData);
437
438
// Load from file
439
cookieManager.loadCookies(new File("saved-cookies.txt"));
440
```
441
442
**Custom Cookie Handling:**
443
444
```java
445
// Create custom cookie manager
446
CookieManager customManager = new CookieManager() {
447
@Override
448
public void addCookie(Cookie cookie) {
449
// Log all cookies being added
450
System.out.println("Adding cookie: " + cookie.getName() + " for " + cookie.getDomain());
451
452
// Only accept cookies from trusted domains
453
if (cookie.getDomain().endsWith(".trusted.com") || cookie.getDomain().equals("localhost")) {
454
super.addCookie(cookie);
455
} else {
456
System.out.println("Rejected cookie from untrusted domain: " + cookie.getDomain());
457
}
458
}
459
};
460
461
webClient.setCookieManager(customManager);
462
```
463
464
### Cookie Security Considerations
465
466
```java { .api }
467
/**
468
* Security-related cookie methods and checks
469
*/
470
public class Cookie {
471
/** Check if cookie has secure attributes for sensitive data */
472
public boolean isSecureForSensitiveData() {
473
return isSecure() && isHttpOnly() && "Strict".equals(getSameSite());
474
}
475
476
/** Create secure cookie for authentication */
477
public static Cookie createSecureAuthCookie(String domain, String name, String value, String path) {
478
Cookie cookie = new Cookie(domain, name, value, path, null, true, true);
479
cookie.setSameSite("Strict");
480
return cookie;
481
}
482
483
/** Create session cookie with security flags */
484
public static Cookie createSecureSessionCookie(String domain, String name, String value) {
485
return createSecureAuthCookie(domain, name, value, "/");
486
}
487
}
488
```
489
490
**Secure Cookie Examples:**
491
492
```java
493
// Create secure authentication cookie
494
Cookie authCookie = Cookie.createSecureAuthCookie("example.com", "authToken", "securetoken123", "/");
495
cookieManager.addCookie(authCookie);
496
497
// Create CSRF protection cookie
498
Cookie csrfCookie = new Cookie("example.com", "csrfToken", "csrf123", "/", null, true, false);
499
csrfCookie.setSameSite("Strict");
500
cookieManager.addCookie(csrfCookie);
501
502
// Check cookie security
503
for (Cookie cookie : cookieManager.getCookies()) {
504
if (cookie.getName().toLowerCase().contains("auth") ||
505
cookie.getName().toLowerCase().contains("session")) {
506
507
if (!cookie.isSecure()) {
508
System.err.println("WARNING: Insecure authentication cookie: " + cookie.getName());
509
}
510
511
if (!cookie.isHttpOnly()) {
512
System.err.println("WARNING: JavaScript-accessible auth cookie: " + cookie.getName());
513
}
514
515
if (!"Strict".equals(cookie.getSameSite()) && !"Lax".equals(cookie.getSameSite())) {
516
System.err.println("WARNING: Missing SameSite protection: " + cookie.getName());
517
}
518
}
519
}
520
```
521
522
### Cookie Debugging and Inspection
523
524
```java
525
// Debug cookie information
526
public void debugCookies(CookieManager cookieManager) {
527
Set<Cookie> cookies = cookieManager.getCookies();
528
529
System.out.println("=== Cookie Debug Information ===");
530
System.out.println("Total cookies: " + cookies.size());
531
System.out.println("Cookies enabled: " + cookieManager.isCookiesEnabled());
532
533
for (Cookie cookie : cookies) {
534
System.out.println("\nCookie: " + cookie.getName());
535
System.out.println(" Value: " + cookie.getValue());
536
System.out.println(" Domain: " + cookie.getDomain());
537
System.out.println(" Path: " + cookie.getPath());
538
System.out.println(" Expires: " + cookie.getExpires());
539
System.out.println(" Max-Age: " + cookie.getMaxAge());
540
System.out.println(" Secure: " + cookie.isSecure());
541
System.out.println(" HttpOnly: " + cookie.isHttpOnly());
542
System.out.println(" SameSite: " + cookie.getSameSite());
543
System.out.println(" Session Cookie: " + cookie.isSessionCookie());
544
System.out.println(" Expired: " + cookie.isExpired());
545
System.out.println(" Version: " + cookie.getVersion());
546
547
if (cookie.getComment() != null) {
548
System.out.println(" Comment: " + cookie.getComment());
549
}
550
}
551
552
// Group by domain
553
Map<String, List<Cookie>> byDomain = cookies.stream()
554
.collect(Collectors.groupingBy(Cookie::getDomain));
555
556
System.out.println("\n=== Cookies by Domain ===");
557
for (Map.Entry<String, List<Cookie>> entry : byDomain.entrySet()) {
558
System.out.println(entry.getKey() + ": " + entry.getValue().size() + " cookies");
559
}
560
}
561
```