1. 概述
在本篇教程中,我们来聊聊如何从 Apache HttpClient 的响应中提取 Cookie。
我们会先介绍如何通过 HttpClient 发送自定义 Cookie,然后再展示如何从响应中获取它。
⚠️ 注意:本文代码示例基于 HttpClient 5.2.x 及以上版本,旧版本 API 不兼容。
2. 在请求中发送 Cookie
在获取响应中的 Cookie 之前,我们首先得发送一个自定义 Cookie。来看下面这段代码:
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value");
cookie.setDomain("baeldung.com");
cookie.setAttribute("domain", "true");
cookie.setPath("/");
cookieStore.addCookie(cookie);
HttpClientContext context = HttpClientContext.create();
context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
try (CloseableHttpClient client = HttpClientBuilder.create()
.build()) {
client.execute(request, context, new BasicHttpClientResponseHandler());
}
✅ 步骤说明:
- 创建一个
BasicCookieStore
实例用于存储 Cookie。 - 构造一个名为
custom_cookie
、值为test_value
的 Cookie。 - 设置该 Cookie 的域、路径等属性。
- 将 Cookie 添加到 CookieStore 中。
- 构造一个
HttpClientContext
,并将 CookieStore 设置进去。 - 最后执行请求时,将上下文传入。
从日志中可以看到 Cookie 被成功发送:
2023-09-13 20:56:59,628 [DEBUG] org.apache.hc.client5.http.headers - http-outgoing-0 >> Cookie: custom_cookie=test_value
3. 从响应中读取 Cookie
发送完 Cookie 后,我们就可以从响应上下文中提取它了:
try (CloseableHttpClient client = HttpClientBuilder.create()
.build()) {
client.execute(request, context, new BasicHttpClientResponseHandler());
CookieStore cookieStore = context.getCookieStore();
Cookie customCookie = cookieStore.getCookies()
.stream()
.peek(cookie -> log.info("cookie name:{}", cookie.getName()))
.filter(cookie -> "custom_cookie".equals(cookie.getName()))
.findFirst()
.orElseThrow(IllegalStateException::new);
assertEquals("test_value", customCookie.getValue());
}
📌 关键点如下:
- 从
HttpClientContext
中拿到CookieStore
。 - 通过
getCookies()
获取所有 Cookie。 - 使用 Java Stream 遍历并筛选出我们想要的 Cookie。
- 最后验证其值是否符合预期。
从日志中可以看到所有 Cookie 名称,包括我们自定义的那个:
[INFO] com.baeldung.httpclient.cookies.HttpClientGettingCookieValueUnitTest - cookie name:_gh_sess
[INFO] com.baeldung.httpclient.cookies.HttpClientGettingCookieValueUnitTest - cookie name:_octo
[INFO] com.baeldung.httpclient.cookies.HttpClientGettingCookieValueUnitTest - cookie name:custom_cookie
4. 总结
通过本文我们学会了如何使用 Apache HttpClient 发送和获取 Cookie。关键点在于:
✅ 使用 HttpClientContext
管理 CookieStore
✅ 请求和响应都通过上下文传递 CookieStore
✅ 使用 Stream API 简洁地筛选目标 Cookie
完整代码已上传至 GitHub:https://github.com/eugenp/tutorials/tree/master/apache-httpclient-2