分享

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

 quasiceo 2014-09-03
分类: Android应用技巧 2014-03-07 16:16 283人阅读 评论(0) 收藏 举报

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

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

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

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

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

多个cookie类似于:
  1.        CookieSyncManager.createInstance(this);  
  2. CookieManager cookieManager = CookieManager.getInstance();  
  3. cookieManager.setAcceptCookie(true);  
  4.   
  5.        for (int i = 0; i < cookieArray.length; i++) {  // cookieArray是多个cookie的数组变量  
  6.            cookieManager.setCookie(mCurrentURL, cookieArray[i] + ";Max-Age=3600" + ";Domain=.163.com" + ";Path = /");  
  7.        }  

写成 
  1. cookieManager.setCookie(".163.com", cookieString);   

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


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

  1. CookieSyncManager.createInstance(this);  
  2.     CookieManager cookieManager = CookieManager.getInstance();  
  3.     cookieManager.setAcceptCookie(true);  
  4.   
  5.         for (int i = 0; i < cookieArray.length; i++) {  // cookieArray是多个cookie的数组变量  
  6.             cookieManager.setCookie("163.com", cookieArray[i] + ";Max-Age=3600" + ";Domain=.163.com" + ";Path = /");  
  7.         }  


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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多