在 Web 应用中获取 Cookie (Servlet/JSP)
这是最经典和常见的情况,在 Servlet 规范中,服务器通过 HttpServletRequest 对象将客户端发送的 Cookie 传递给后端。

获取单个 Cookie
你可以通过 Cookie 的名称来获取特定的 Cookie。
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class CookieExample extends javax.servlet.http.HttpServlet {
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
// 1. 通过名称获取指定的 Cookie
// 注意:Cookie 不存在,此方法返回 null
Cookie usernameCookie = request.getCookie("username");
if (usernameCookie != null) {
// 2. 从 Cookie 对象中获取值
String username = usernameCookie.getValue();
System.out.println("从 Cookie 中获取到的用户名是: " + username);
// 3. 还可以获取其他属性,如路径、域名、最大生存时间等
String path = usernameCookie.getPath();
int maxAge = usernameCookie.getMaxAge();
System.out.println("Cookie 路径: " + path);
System.out.println("Cookie 最大存活时间(秒): " + maxAge);
} else {
System.out.println("未找到名为 'username' 的 Cookie。");
}
}
}
获取所有 Cookie
客户端可能发送了多个 Cookie,你可以一次性获取所有 Cookie。
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class GetAllCookiesExample extends javax.servlet.http.HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 获取请求中所有的 Cookie
// 如果请求中没有 Cookie,此方法返回 null
Cookie[] cookies = request.getCookies();
if (cookies != null) {
System.out.println("当前请求中的所有 Cookie:");
// 2. 遍历 Cookie 数组
for (Cookie cookie : cookies) {
System.out.println("名称: " + cookie.getName() + ", 值: " + cookie.getValue());
}
} else {
System.out.println("当前请求中没有携带任何 Cookie。");
}
}
}
JSP 中获取 Cookie
在 JSP 页面中,获取 Cookie 更加直接和方便。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="javax.servlet.http.Cookie" %>
<%@ page import="javax.servlet.http.HttpServletRequest" %>
<html>
<head>获取 Cookie 示例</title>
</head>
<body>
<h1>从 JSP 获取 Cookie</h1>
<%
// 1. 直接使用 request 对象获取所有 Cookie
Cookie[] cookies = request.getCookies();
if (cookies != null) {
out.println("<h2>当前请求中的所有 Cookie:</h2>");
for (Cookie cookie : cookies) {
// 2. 输出 Cookie 的名称和值
out.println("Cookie Name: " + cookie.getName() + ", Value: " + cookie.getValue() + "<br>");
}
} else {
out.println("<p>当前请求中没有携带任何 Cookie。</p>");
}
%>
</body>
</html>
在 Java 客户端程序中获取 Cookie
当你使用 Java 编写一个爬虫、API 测试工具或任何需要与服务器交互的客户端程序时,你需要自己处理 HTTP 请求和响应,并手动提取和管理 Cookie。

使用 java.net.HttpURLConnection
这是 Java 标准库自带的 HTTP 客户端,功能相对基础。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientCookieExample {
public static void main(String[] args) throws IOException {
// 1. 创建一个 CookieManager 来自动处理 Cookie
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager); // 设置为全局的 Cookie 处理器
URL url = new URL("http://www.example.com/login"); // 假设这个登录接口会设置 Cookie
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 2. 发送 GET 请求
connection.setRequestMethod("GET");
// 3. 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 4. 从响应头中获取 Set-Cookie 字段
// 注意:CookieManager 会自动将 Set-Cookie 存储起来,但如果你想手动查看,可以这样做
String headerName;
for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equalsIgnoreCase("Set-Cookie")) {
String cookie = connection.getHeaderField(i);
System.out.println("Set-Cookie Header: " + cookie);
}
}
// 5. 读取响应体(如果需要)
if (responseCode == HttpURLConnection.HTTP_OK) { // 200
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response Body: " + response.toString());
}
// 6. 当你向同一个域名的其他 URL 发送请求时,CookieManager 会自动附加之前存储的 Cookie
URL anotherUrl = new URL("http://www.example.com/profile");
HttpURLConnection anotherConnection = (HttpURLConnection) anotherUrl.openConnection();
anotherConnection.setRequestMethod("GET");
// 不需要手动设置 Cookie,CookieManager 会自动处理
System.out.println("访问 profile 页面,请求会自动带上之前获取的 Cookie。");
anotherConnection.disconnect();
}
}
使用第三方库 (推荐: OkHttp)
在实际开发中,使用 HttpURLConnection 会比较繁琐,推荐功能更强大、更易用的第三方库,如 OkHttp。
添加 Maven 依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version> <!-- 请使用最新版本 -->
</dependency>
使用 OkHttp 获取 Cookie 非常简单:

import okhttp3.*;
import java.io.IOException;
import java.util.List;
public class OkHttpCookieExample {
public static void main(String[] args) throws IOException {
// 1. 创建 OkHttp 客户端
OkHttpClient client = new OkHttpClient();
// 2. 创建一个请求
Request request = new Request.Builder()
.url("http://www.example.com/login")
.build();
// 3. 执行请求
try (Response response = client.newCall(request).execute()) {
// 4. 从响应中获取 Cookie
List<String> cookies = response.headers("Set-Cookie");
System.out.println("从服务器收到的 Set-Cookie:");
for (String cookie : cookies) {
System.out.println(cookie);
}
// 5. OkHttp 会自动将 Cookie 存储在内存中,并在后续请求中自动发送
// 访问需要登录的页面
Request profileRequest = new Request.Builder()
.url("http://www.example.com/profile")
.build();
try (Response profileResponse = client.newCall(profileRequest).execute()) {
System.out.println("\n访问 profile 页面的响应码: " + profileResponse.code());
// profileResponse.body().string(); // 读取响应体...
}
}
}
}
OkHttp 的 CookieJar 接口允许你自定义 Cookie 的存储策略(持久化到磁盘),非常灵活。
| 场景 | 核心对象/方法 | 关键点 |
|---|---|---|
| Web 应用 (Servlet) | HttpServletRequest.getCookie(name) 或 request.getCookies() |
服务器端自动处理,直接从请求对象获取。 |
| Web 应用 (JSP) | request.getCookies() |
语法更简洁,可以直接在页面脚本中使用。 |
| Java 客户端 (标准库) | java.net.CookieHandler, HttpURLConnection.getHeaderField("Set-Cookie") |
需要手动管理 Cookie,代码较繁琐。 |
| Java 客户端 (推荐) | OkHttp | 自动管理 Cookie,API 简洁强大,是现代 Java HTTP 客户端的首选。 |
根据你的具体需求选择合适的方法,如果是 Web 开发,使用 HttpServletRequest;如果是编写客户端工具,强烈推荐使用 OkHttp。
