首页 > 移动平台 > 详细

android WebView 保存cookie

时间:2021-06-25 16:59:08      阅读:18      评论:0      收藏:0      [点我收藏+]

 

    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;
    }

 

android WebView 保存cookie

原文:https://www.cnblogs.com/beastGentleman/p/14931119.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!