这两天有个项目需求要用cookie 缓存 免登录, 在网上找了好多相关教程, 没有一个完整可以测试的。 经历了重重磨难终于... 突破了... 突破了... 突破了... 下面为实例代码
package com.example.lin.webbrower; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.net.http.SslError; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.SslErrorHandler; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import static android.webkit.CookieSyncManager.createInstance; import static android.webkit.CookieSyncManager.getInstance; /** * Created by LIN on 2018/8/1. * web浏览器 */ public class WebBrowerActivity extends AppCompatActivity { WebView webView; private String url; private CookieManager mCookieManager; private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_webbrower); setTitle("加载中..."); webView = (WebView) findViewById(R.id.web_view); //获取sharedPreferences对象 sharedPreferences = getSharedPreferences("myshare", Context.MODE_PRIVATE); //获取editor对象 //获取编辑器 editor = sharedPreferences.edit(); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true);//支持js //settings.setPluginState(true);//支持插件 settings.setUseWideViewPort(false);//将图片调整到适合webview的大小 settings.setSupportZoom(true);//支持缩放 settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局 settings.supportMultipleWindows();//多窗口 settings.setAllowFileAccess(true);//设置可以访问文件 settings.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点 settings.setBuiltInZoomControls(true); //设置支持缩放 settings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小 settings.setCacheMode(WebSettings.LOAD_NO_CACHE); settings.setAppCacheEnabled(true); settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); settings.setLoadsImagesAutomatically(true);//支持自动加载图片 String cookiea = sharedPreferences.getString(url, ""); //测试可用 String cookie = "这里为关键cookie串 用户名 权限 等信息; domain=通过抓包工具得到; expires=Sat, 03-Aug-2019 14:01:48 GMT; path=/"; //同步cookie 到 url 中 if (cookiea != null) { syncCookie(url, cookiea); } webView.loadUrl(url); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { //这里一定要是url不能是网页 view.loadUrl(url); return true; }//证书的设置支持所有的证书 @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); CookieManager cookieManager = CookieManager.getInstance(); String cookie = cookieManager.getCookie(url); String lastUser = cookie.substring(cookie.indexOf("UsUser"), cookie.length()); editor.putString(url, lastUser); editor.commit(); String title = view.getTitle(); if (!TextUtils.isEmpty(title)) { setTitle(title); } } }); } private void syncCookie(String url, String cookie) { try { createInstance(this);//创建一个cookie管理器 CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); cookieManager.removeSessionCookie();// 移除以前的cookie cookieManager.removeAllCookie(); StringBuilder sbCookie = new StringBuilder();//创建一个拼接cookie的容器,为什么这么拼接,大家查阅一下http头Cookie的结构 sbCookie.append(cookie); //这里的两个key很重要,如果不知道是什么可以抓包得到 sbCookie.append(String.format(";domain=%s", ".")); sbCookie.append(String.format(";path=%s", "/")); String cookieValue = sbCookie.toString(); cookieManager.setCookie(url, cookieValue);//为url设置cookie getInstance().sync();//同步cookie } catch (Exception e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); } //防止退出的时候抛Zoom异常 @Override public void finish() { ViewGroup view = (ViewGroup) getWindow().getDecorView(); view.removeAllViews(); super.finish(); } }