Android WebView保存Cookie登陸

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

/**
* 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);
            }

            StringBuilder sbCookie = new StringBuilder();
            sbCookie.append(String.format("JSESSIONID=%s","INPUT YOUR JSESSIONID STRING"));
            sbCookie.append(String.format(";domain=%s", "INPUT YOUR DOMAIN STRING"));
            sbCookie.append(String.format(";path=%s","INPUT YOUR PATH STRING"));

            String cookieValue = sbCookie.toString();
            cookieManager.setCookie(url, cookieValue);
            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());
        }
    }


使用上面的方法能夠將Cookie同步到WebView中,這樣瀏覽網頁時便可實現免登陸。web

可是在實際使用過程當中發現Cookie並未保存成功,每次都會跳轉到登陸頁面,糾結了好久,終於發現是在初始化WebView時漏掉了重要的東西。能夠參考下面個人代碼設置WebView。cookie

/**
* 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);
    }


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

第一使用WebView控件,原覺得很簡單,但是一不當心就掉坑裏去了,你們當心。dom

相關文章
相關標籤/搜索