最近做了一个项目要用到COOKIE, 保存登录记录,试了好多方法都不行, 终于使用下面的办法可以解决这个问题。
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebview = (WebView) findViewById(R.id.webview); btnGoPayment = (Button)findViewById(R.id.btngopayment); beginLoading = (TextView) findViewById(R.id.text_beginLoading); endLoading = (TextView) findViewById(R.id.text_endLoading); loading = (TextView) findViewById(R.id.text_Loading); configWebView(mWebview); //一定要加上这部分,否则第二次登录仍然需要输入密码 CookieManager.getInstance().setAcceptThirdPartyCookies(mWebview,true); String url = "http://sg.hanxe.com/my/paypal/bra"; btnGoPayment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //一定要加上支持第三方COOKIE,否则拿不到登录COOKIE CookieManager.getInstance().setAcceptThirdPartyCookies(mWebview,true); mWebview.loadUrl("http://sg.hanxe.com/my/paypal/bra");//加载url } }); //设置不用系统浏览器打开,直接显示在当前Webview mWebview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.i("paypal","shouldOverrideUrlLoading:" + url); view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) {//页面加载完成 CookieSyncManager.createInstance(getApplicationContext()); Log.i("paypal","onPageFinished:" + url); CookieManager cookieManager = CookieManager.getInstance(); String CookieStr = cookieManager.getCookie(url); Log.i("Cookies", "Cookies = " + CookieStr); super.onPageFinished(view, url); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载 Log.i("paypal","onPageStarted:" + url); } public void onLoadResource(WebView view, String url) { // 分享 Log.i("paypal","onLoadResource:" + url); boolean isCook = false; String cookie = getSharedPreferences("cookie", Context.MODE_PRIVATE).getString("cookies", ""); if(!cookie.equals("")){ isCook = true; } Log.i("testpaypal","isCook:"+ isCook); //CookieSyncManager.createInstance(getApplicationContext()); CookieManager cookieManager = CookieManager.getInstance(); String cookieStr = cookieManager.getCookie(getDomain(url)); Log.i("testpaypal","cookieStr:"+ cookieStr); if (url.contains("https://www.sandbox.paypal.com/webapps/hermes/button?")) { Log.i("testpaypal","url:"+ url); if(!isCook){ if(cookieStr != null){ Log.i("testpaypal","cookieold:"+ cookieStr); String[] cookieArray = cookieStr.split(";");// 多个Cookie是使用分号分隔的 for (int i = 0; i < cookieArray.length; i++) { int position = cookieArray[i].indexOf("=");// 在Cookie中键值使用等号分隔 String cookieName = cookieArray[i].substring(0, position);// 获取键 String cookieValue = cookieArray[i].substring(position + 1);// 获取值 String value = cookieName + "=" + cookieValue;// 键值对拼接成 value Log.i("cookie", value); synCookies(getApplicationContext(),getDomain(url), value);// 设置 Cookie } SharedPreferences preferences = getSharedPreferences("cookie", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("cookies", cookieStr); editor.commit(); } }else{ Log.i("testpaypal","isCook:"+ isCook); String cookie1 = getSharedPreferences("cookie", Context.MODE_PRIVATE).getString("cookies", ""); Log.i("testpaypal","cookienew:"+ cookie1); CookieManager.getInstance().setAcceptCookie(true); String[] cookieArray = cookie1.split(";");// 多个Cookie是使用分号分隔的 for (int i = 0; i < cookieArray.length; i++) { int position = cookieArray[i].indexOf("=");// 在Cookie中键值使用等号分隔 String cookieName = cookieArray[i].substring(0, position);// 获取键 String cookieValue = cookieArray[i].substring(position + 1);// 获取值 String value = cookieName + "=" + cookieValue;// 键值对拼接成 value Log.i("cookie", value); synCookies(getApplicationContext(),getDomain(url), value);// 设置 Cookie } //cookieManager.setCookie(getDomain(url), cookie1); } } super.onLoadResource(view, url); } }); //设置WebChromeClient类 mWebview.setWebChromeClient(new WebChromeClient() { //获取网站标题 @Override public void onReceivedTitle(WebView view, String title) { System.out.println("标题在这里"); //mtitle.setText(title); } //获取加载进度 @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress < 100) { String progress = newProgress + "%"; loading.setText(progress); } else if (newProgress == 100) { String progress = newProgress + "%"; loading.setText(progress); } } }); mWebview.loadUrl(url); } private String getDomain(String url) { url = url.replace("http://", "").replace("https://", ""); if (url.contains("/")) { url = url.substring(0, url.indexOf('/')); } return url; } /** * 设置Cookie * * @param context * @param url * @param cookie 格式:uid=21233 如需设置多个,需要多次调用 */ public void synCookies(Context context, String url, String cookie) { CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); CookieManager.getInstance().setAcceptThirdPartyCookies(mWebview,true); cookieManager.setAcceptCookie(true); cookieManager.setCookie(url, cookie);//cookies是在HttpClient中获得的cookie CookieSyncManager.getInstance().sync(); } /** * 清除Cookie * * @param context */ public static void removeCookie(Context context) { CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); CookieSyncManager.getInstance().sync(); } protected void configWebView(WebView webView) { //启用数据库 webView.getSettings().setDatabaseEnabled(true); //设置定位的数据库路径 String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); webView.getSettings().setGeolocationDatabasePath(dir); //启用地理定位 webView.getSettings().setGeolocationEnabled(true); //开启DomStorage缓存 webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setLoadsImagesAutomatically(true); webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); webView.getSettings().setAppCacheMaxSize(1024*1024*8); String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath(); webView.getSettings().setAppCachePath(appCachePath); webView.getSettings().setAllowFileAccess(true); webView.getSettings().setAppCacheEnabled(true); webView.getSettings().setJavaScriptEnabled(true); String ua = webView.getSettings().getUserAgentString(); Log.i("testpaypal",ua); //webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); //webView.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/_BuildID_) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36"); //webView.setWebViewClient(new WebViewClient(){}); //webView.setWebChromeClient(new WebChromeClient()); }
完整DEMO下载地址:
链接:https://pan.baidu.com/s/1DCQypeZ5q1iOlznQgYZ9DA
提取码:9ge7
复制这段内容后打开百度网盘手机App,操作更方便哦