java 27 lines · 6 steps

Parsing an HTTP Cookie header in Java

Split a raw Cookie header into an ordered map of names to decoded values, defensively skipping malformed pieces.

Explained by highlit
1public static Map<String, String> parseCookieHeader(String header) {
2 Map<String, String> cookies = new LinkedHashMap<>();
3 if (header == null || header.isBlank()) {
4 return cookies;
5 }
6 
7 for (String pair : header.split(";")) {
8 int eq = pair.indexOf('=');
9 if (eq < 0) {
10 continue;
11 }
12 
13 String name = pair.substring(0, eq).trim();
14 if (name.isEmpty()) {
15 continue;
16 }
17 
18 String value = pair.substring(eq + 1).trim();
19 if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
20 value = value.substring(1, value.length() - 1);
21 }
22 
23 cookies.putIfAbsent(name, URLDecoder.decode(value, StandardCharsets.UTF_8));
24 }
25 
26 return cookies;
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Guard against null and empty input up front so the happy path stays clean.
  2. 2Skip malformed entries with continue instead of throwing, keeping the parser tolerant of real-world headers.
  3. 3Preserving insertion order and honoring first-wins semantics matters when duplicate cookie names appear.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing an HTTP Cookie header in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code