Android WebView保存Cookie登錄

因項目需要,需要在App中嵌入網頁,使用Nativie方式登錄,然後將cookie保存到WebView中,實現免登錄功能。同步Cookie到WebView的方法網上有大量的參考資料,也可以參考下面的代碼:

/**
* Sync Cookie
*/
private void syncCookie(Context context, String url){
try{
Log.d(“Nat: webView.syncCookie.url”, url);

            CookieSyncManager.createInstance(context);

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);
            if(oldCookie != null){
                Log.d("Nat: webView.syncCookieOutter.oldCookie", oldCookie);
            }

            PersistentCookieStore persistentCookieStore = MyApplication
                    .getInstance().getCookieStore();
            for (Cookie cookie : persistentCookieStore.getCookies()) {

                String cookieString = cookie.getName() + "=" + cookie.getValue()
                        + "; domain=" + cookie.getDomain()
                        + "; path=" + cookie.getPath();
                cookieManager.setCookie(url, cookieString);
                CookieSyncManager.getInstance().sync();
            }
            String newCookie = cookieManager.getCookie(url);
            if(newCookie != null){
                Log.d("Nat: webView.syncCookie.newCookie", newCookie);
            }
        }catch(Exception e){
            Log.e("Nat: webView.syncCookie failed", e.toString());
        }
    }

來自CODE的代碼片
shareCookie.java

使用上面的方法可以將Cookie同步到WebView中,這樣瀏覽網頁時即可實現免登錄。
但是在實際使用過程中發現Cookie並未保存成功,每次都會跳轉到登錄頁面,糾結了很久,終於發現是在初始化WebView時漏掉了重要的東西。可以參考下面我的代碼設置WebView。

[java] view plain copy
/**
* init WebView Settings
* */
private void initWebViewSettings(){
// myWebView.getSettings().setSupportZoom(true);
// myWebView.getSettings().setBuiltInZoomControls(true);
// myWebView.getSettings().setDefaultFontSize(12);
// myWebView.getSettings().setLoadWithOverviewMode(true);
// 設置可以訪問文件
myWebView.getSettings().setAllowFileAccess(true);
//如果訪問的頁面中有Javascript,則webview必須設置支持Javascript
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setUserAgentString(MyApplication.getUserAgent());
myWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
}

完成以上兩步操作,再次運行程序,你會發現,打開網頁後不會再跳轉到登錄頁面了。

第一使用WebView控件,原以爲很簡單,可是一不小心就掉坑裏去了,大家小心。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章