在Android的WebView中给一级域名设置cookie

        在手机上有时候访问网页,需要app传递用户的信息,需要用到cookie。大多数人都知道是调用cookieManager.setCookie(url, value), 但不知道怎么讲一级域名的cookie设置到CookieManager中。其实很简单,看看CookieManager.setCookie的注释就知道了

     /**
     * Sets a cookie for the given URL. Any existing cookie with the same host,
     * path and name will be replaced with the new cookie. The cookie being set
     * must not have expired and must not be a session cookie, otherwise it
     * will be ignored.
     *
     * @param url the URL for which the cookie is set
     * @param value the cookie as a string, using the format of the 'Set-Cookie'
     *              HTTP response header
     */
    public void setCookie(String url, String value) {
        throw new MustOverrideException();
    }

url参数是你要为哪个cookie设置,而value和服务器返回设置sookie的方法'Set-Cookie‘是一致的。

也就是一个url的多个cookie,要调用多次setCookie,而每一次调用value的值都类似于:

cookie + ";Max-Age=3600" + ";Domain=.163.com" + ";Path = /"  // 当然还可以加上版本等信息

多个cookie类似于:

        CookieSyncManager.createInstance(this);
	CookieManager cookieManager = CookieManager.getInstance();
	cookieManager.setAcceptCookie(true);

        for (int i = 0; i < cookieArray.length; i++) {  // cookieArray是多个cookie的数组变量
            cookieManager.setCookie(mCurrentURL, cookieArray[i] + ";Max-Age=3600" + ";Domain=.163.com" + ";Path = /");
        }

写成 

cookieManager.setCookie(".163.com", cookieString); 

是完全错误的,第一个参数是你访问的网址,不是cookie存储的域名,和cookie有关的信息全部都要放在第二个参数里。


       设置cookie用mCurrentURL在4.0下可能出现post的数据没有cookie或者不完全的情况,那就要用一级域名设置cookie,这样各种版本都不会有什么问题。

CookieSyncManager.createInstance(this);
	CookieManager cookieManager = CookieManager.getInstance();
	cookieManager.setAcceptCookie(true);

        for (int i = 0; i < cookieArray.length; i++) {  // cookieArray是多个cookie的数组变量
            cookieManager.setCookie("163.com", cookieArray[i] + ";Max-Age=3600" + ";Domain=.163.com" + ";Path = /");
        }


       另一个要注意的事项是cookie要在setting设置完之后设置,不然无效。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值