Parse Cookie Headers With HttpCookie

Parse Set-Cookie style headers with HttpCookie.parse, read attributes, then rebuild a Cookie request header from a small jar.

JavaAuth Jwt

Code

snippet
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;

public class HttpCookieDemo {
    public static void main(String[] args) {
        // parse 接受完整的 Set-Cookie 字符串
        List<HttpCookie> cookies = HttpCookie.parse(
                "session=abc123; Path=/app; Max-Age=3600; HttpOnly; Secure");
        HttpCookie cookie = cookies.get(0);
        System.out.println("name: " + cookie.getName());
        System.out.println("value: " + cookie.getValue());
        System.out.println("path: " + cookie.getPath());
        System.out.println("max age: " + cookie.getMaxAge());
        System.out.println("http only: " + cookie.isHttpOnly());
        System.out.println("secure: " + cookie.getSecure());

        // 同一域下可维护多个 Cookie 的列表
        HttpCookie theme = new HttpCookie("theme", "dark");
        theme.setPath("/");
        theme.setVersion(1);
        List<HttpCookie> jar = new ArrayList<>();
        jar.add(cookie);
        jar.add(theme);

        // Cookie 请求头按 name=value 拼接,属性不进请求
        StringBuilder header = new StringBuilder();
        for (HttpCookie item : jar) {
            if (header.length() > 0) {
                header.append("; ");
            }
            header.append(item.getName()).append('=').append(item.getValue());
        }
        System.out.println("cookie header: " + header);

        // 过期判断依赖 max age 与创建时间
        System.out.println("has expired: " + cookie.hasExpired());
    }
}

How the snippet works

The working surface is the class HttpCookieDemo and the function main — everything else is wiring.

for (HttpCookie item : jar) is the loop that carries the per-item work.

Using it

The run emits 8 labeled sections — name:, value:, path:, max age:, http only:, secure:, cookie header:, has expired: — one per step.

Key statements

header.append(item.getName()).append('=').append(item.getValue());
HttpCookie theme = new HttpCookie("theme", "dark");
StringBuilder header = new StringBuilder();

Interactive Tools for This Topic

FAQ

What does Parse Cookie Headers With HttpCookie print when run?
Run it as a complete program — the output lines carry labels such as `name:`, `value:`, `path:`.