问题描述
当我使用 HttpURLConnection
并尝试 con.getHeaderField( Set-Cookie)
时,我得到以下响应:
When I use HttpURLConnection
and try con.getHeaderField("Set-Cookie")
I get this response:
__cfduid=1111111aaaaaa; expires=Wed, 19-Dec-18 06:19:46 GMT; path=/; domain=.site.com; HttpOnly
但是浏览器cookie是:
But the browser cookies are:
__cfduid=1111111aaaaaa; _ym_uid=000000000; PHPSESSID=zzzzzzzz; _ym_isad=1; key=555
如何使用 HttpURLConnection获取完整的Cookie ?对我来说,最重要的cookie是
key
。
How I can get the FULL cookie, using
HttpURLConnection
? The most important cookie for me is key
.
推荐答案
Set-cookie
标头的值修改或附加新值浏览器中的Cookie。并且浏览器从cookie中删除过期的cookie。
The value of
Set-cookie
header modify or append new value to Cookies in browser. And browser delete expired cookie from cookies. The assembling work completed by browser.
当用Java请求Web时,程序员需要通过
Set-cookie 单个或多个响应中的标头。
When request web in java, programmer need assemble 'full' cookies by
Set-cookie
header in single or multi responses.
如果使用
HttpURLConnection
,则可以使用
If you use
HttpURLConnection
, you can use CookieManager
这是一个示例
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
URL url = new URL("https://stackoverflow.com");
URLConnection connection = url.openConnection();
connection.getContent();
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
for (HttpCookie cookie : cookies) {
System.out.println(cookie.getDomain());
System.out.println(cookie);
}
发送HTTP请求时,
CookieManager
将自动填充Cookie标头。而且,该值可以直接从 CookieManger
按域实现。
When you send HTTP request,
CookieManager
will auto fill Cookie Header. And, the value can be directly achieved from CookieManger
by domain.
这篇关于如何在Java中使用HttpURLConnection获取Cookies?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!