public void setCookies(String cookiesPath) { Map<String, String> cookieMap = new HashMap<>(); String cookie = getSharedPreferences("cookie", Context.MODE_PRIVATE).getString("cookies", "");// 从SharedPreferences中获取整个Cookie串 if (!TextUtils.isEmpty(cookie)) { String[] cookieArray = cookie.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); CookieManager.getInstance().setCookie(getDomain(cookiesPath), value);// 设置 Cookie } } }
@Override protected void onDestroy() { super.onDestroy(); CookieManager cookieManager = CookieManager.getInstance(); String cookieStr = cookieManager.getCookie(getDomain("http://192.168.10.227/#/everwin/wip")); SharedPreferences preferences = getSharedPreferences("cookie", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("cookies", cookieStr); editor.commit(); } /** * 获取URL的域名 */ private String getDomain(String url) { url = url.replace("http://", "").replace("https://", ""); if (url.contains("/")) { url = url.substring(0, url.indexOf(‘/‘)); } return url; }