实现说明
底层就是类 HttpCookieDemo和函数 main。
for (HttpCookie item : jar) 承担全部的逐项处理。
使用要点
- 演示输出是带标签的(
name:、value:、path:),每个操作都会留下自己的一行标注。
常见问题
运行「HttpCookie 解析 Cookie 头」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 name:、value:、path: 标签标明各步骤。
核心语句
header.append(item.getName()).append('=').append(item.getValue());
HttpCookie theme = new HttpCookie("theme", "dark");
StringBuilder header = new StringBuilder();
代码示例
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());
}
}