java 如何取cookie
获取 Cookie 的方法
在 Java 中获取 Cookie 通常涉及 HTTP 请求的处理,可以通过 HttpServletRequest 或第三方库(如 Apache HttpClient、OkHttp)实现。
使用 HttpServletRequest(Servlet 环境)
在 Servlet 中,可以通过 HttpServletRequest 对象直接获取 Cookie 数组:

Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("Cookie Name: " + name + ", Value: " + value);
}
}
使用 Apache HttpClient
通过 HttpClient 发送请求后,可以从响应中提取 Cookie:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
CookieStore cookieStore = new BasicCookieStore();
HttpContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {
System.out.println("Cookie: " + cookie.getName() + "=" + cookie.getValue());
}
使用 OkHttp
通过 OkHttp 的 Response 对象可以获取 Cookie 头信息:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com")
.build();
Response response = client.newCall(request).execute();
String cookiesHeader = response.header("Set-Cookie");
System.out.println("Cookies: " + cookiesHeader);
使用 Java 11+ 的 HttpClient
Java 11 引入的 HttpClient 也支持 Cookie 处理:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Optional<String> cookies = response.headers().firstValue("Set-Cookie");
cookies.ifPresent(System.out::println);
注意事项
- 如果使用 Servlet 方式,需确保在 Web 容器(如 Tomcat)中运行。
- 第三方库需添加依赖(如 Apache HttpClient 或 OkHttp)。
- Cookie 可能包含敏感信息,需注意安全处理。






