How to get Cookies with HttpURLConnection in Java?

强颜欢笑 提交于 2019-12-22 09:57:51

问题


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

But the browser cookies are:

__cfduid=1111111aaaaaa; _ym_uid=000000000; PHPSESSID=zzzzzzzz; _ym_isad=1; key=555

How I can get the FULL cookie, using HttpURLConnection? The most important cookie for me is key.


回答1:


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.

When request web in java, programmer need assemble 'full' cookies by Set-cookie header in single or multi responses.

If you use HttpURLConnection, you can use CookieManager

This is an example

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);
}

When you send HTTP request, CookieManager will auto fill Cookie Header. And, the value can be directly achieved from CookieManger by domain.



来源:https://stackoverflow.com/questions/47881165/how-to-get-cookies-with-httpurlconnection-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!