webview 同步Cookie,保存本地方式

public class SyncWebCookies {

    public static final String COOKIE_KEY = "web_cook_key";

    public static void saveWebCookies(String url) {
        CookieManager cookieManager = CookieManager.getInstance();
        String mycookie = cookieManager.getCookie(url);
        LinkDoodApplication.sharedPreferenceUtil.putString(COOKIE_KEY,mycookie);
    }

    public static void  synchronousWebCookies(String url) {
        CookieManager cookieManager = CookieManager.getInstance();
        String aaaacookies = cookieManager.getCookie(url);

        String cookies = LinkDoodApplication.sharedPreferenceUtil.getString(COOKIE_KEY);

        if (!TextUtils.isEmpty(cookies)) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                CookieSyncManager.createInstance(LinkDoodApplication.mContext);
            }
            cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            StringBuilder sbCookie = new StringBuilder();//创建一个拼接cookie的容器,为什么这么拼接,大家查阅一下http头Cookie的结构
            sbCookie.append(cookies);//拼接sessionId
            sbCookie.append(String.format(";domain=%s", ""));
            sbCookie.append(String.format(";path=%s", ""));
            String cookieValue = sbCookie.toString();
            cookieManager.setCookie(url, cookieValue);//为url设置cookie
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                CookieManager.getInstance().flush();
            }else{
                CookieSyncManager.getInstance().sync();//同步cookie
            }
        }
    }
}

 

你可能感兴趣的:(webview 同步Cookie,保存本地方式)