關於Android使用Xutils的WebView儲存Cookie登入
阿新 • • 發佈:2019-01-29
/** * 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"));//上面儲存的sessionid 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()); } } /** * 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("User-Agent:Android"); myWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); myWebView.getSettings().setAllowFileAccess(true); myWebView.getSettings().setAppCacheEnabled(true); myWebView.getSettings().setDomStorageEnabled(true); myWebView.getSettings().setDatabaseEnabled(true); }