如何使用在Android客户端维护会话的cookie?

时间:2014-11-10 05:04:05

标签: android session-cookies

文档读取有关类Cookie的信息:“Cookie,HTTP”magic-cookie“表示HTTP代理和目标服务器可以交换以保持会话的状态信息。”但是如何使用这种魔力呢?谁能说出来?具体来说,我想使用cookie来维护浏览器端的会话。怎么做?

2 个答案:

答案 0 :(得分:0)

尝试下面的代码来维护Cookie,它对我来说没问题: -

            CookieStore cookieStore = new BasicCookieStore();

            // Create local HTTP context
            HttpClientContext localContext = HttpClientContext.create();
            // Bind custom cookie store to the local context
            localContext.setCookieStore(cookieStore);

            HttpGet httpget = new HttpGet("http://localhost/");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Pass local context as a parameter
            CloseableHttpResponse response = httpclient.execute(httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                List<Cookie> cookies = cookieStore.getCookies();
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("Local cookie: " + cookies.get(i));
                }
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }

答案 1 :(得分:0)

在收到Http请求的回复后,只需添加以下代码:

public static List<Cookie> cookies;
try {
        cookies = httpclient.getCookieStore().getCookies();
        sync();
    } catch (Exception e) {
    }

//Sync Method:

    public void sync() {
            if (cookies != null) {

                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setAcceptCookie(true);
                for (Cookie cookie : cookies) {

                    Cookie sessionInfo = cookie;
                    String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
                    cookieManager.setCookie(YOUR DOMAIN, cookieString);
                    CookieSyncManager.getInstance().sync();
                }
            }
        }