最近在做項目時用到了webview打開指定鏈接的網頁,可已經把webview設置了cookie但始終跳轉到登錄頁面,這明顯是cookie沒有設置成功導致webview沒有將設置好的cookie發送出去……
1
2
3
4
5
|
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(
true
);
cookieManager.setCookie(url, cookies);
//cookies是在HttpClient中獲得的cookie
CookieSyncManager.getInstance().sync();
|
通過上述代碼即可把事先保存下來的cookie和指定的url關聯起來,達到保持登錄的狀態,避免重復登錄。遺憾的是,筆者在開發過程當中嚴格按照上述設置cookie的代碼來進行cookie的設置,可結果還是失敗,始終跳轉到登錄頁提示登錄。后來返回去查看了下Android API文檔,發現setCookie函數的兩個參數值說明如下:
public void setCookie(String url, String value)
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.
url | the URL for which the cookie is set |
---|---|
value | the cookie as a string, using the format of the 'Set-Cookie' HTTP response header value參數的作用是cookie值的字符串形式,但格式一定要是http請求頭格式"Set-Cookie"。 |
原文鏈接:http://www.cnblogs.com/hdtianfu/archive/2013/05/30/3108295.html
Cookie相關的Http頭
一個URL中包含有domain和path,可以參考http://www.w3school.com.cn/html/html_url.asp
在程序中生成expires
上述紅色加粗的文字更讓我確信了我的判斷,此時此刻的心情有多么激動就不用說了,嘿嘿
於是,我在原來設置的cookie字符串上加上了domain和path字段,懷着期盼的心情run了下,哈哈,結果正確了,再也不用反復登錄了。
經過此次的bug解決,在編程中不能放過任何一個細節,要對每個運行細節都清清楚楚這樣才能避免盲目的去解決問題,最終浪費時間……
歡迎加入討論群討論:192209234