How to get cookies in HttpUrlConnection by using CookieStore?

青春壹個敷衍的年華 提交于 2019-12-03 00:40:18

Use this to set cookies.

First, set upcookieManager:

    cookieManager = new java.net.CookieManager();
    CookieHandler.setDefault(cookieManager);
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

Next, set cookies to HttpUrlConnection by setRequestProperty()

        if (cookieManager.getCookieStore().getCookies().size() > 0) {

            List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();

            if (cookies != null) {
                for (HttpCookie cookie : cookies) {
                    conn.setRequestProperty("Cookie", cookie.getName() + "=" + cookie.getValue());
                }
            }
        }
HenryChuang

set cookie :

conn.setRequestProperty("Cookie", "cookieName=cookieValue; domain=www.test.com");

get cookie :

Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get("Set-Cookie");
if(cookiesHeader != null){
    String cookie = cookiesHeader.get(0);
    HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
    String name = httpCookie.getName(); 
    String value = httpCookie.getValue();
    String domain = httpCookie.getDomain();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!