在手机上有时候访问网页,需要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设置完之后设置,不然无效。
|