0

webview 设置OkHttp 3 里面使用的 cookie

sandra 发布于2年前 阅读数 2364

OkHttp 里面使用的PersistentCookieJar管理的Cookie

https://github.com/franmontiel/PersistentCookieJar

现在Webview里面的h5也需要使用和API相同的接口怎样设置?

举报
回复
0

很简单,参考下面的代码。

public class CookiesSynUtils {

    public static void synCookies(String url) {
        SharedPrefsCookiePersistor cookiePersistor = new SharedPrefsCookiePersistor(MyApplication.getContext());

        CookieSyncManager.createInstance(MyApplication.getContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        List<Cookie> cookies=cookiePersistor.loadAll();

        StringBuffer sb = new StringBuffer();

        for ( Cookie cookie : cookies)
        {
            String cookieName = cookie.name();
            String cookieValue = cookie.value();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }

        String[] cookie = sb.toString().split(";");
        for (int i = 0; i < cookie.length; i++) {
            //LogUtils.d("cookie[i]:"+cookie[i]);
            cookieManager.setCookie(url, cookie[i]);// cookies是在HttpClient中获得的cookie
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush();
        } else {
            CookieSyncManager.getInstance().sync();
        }
    }

    public static void clearCookies(){
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();// 移除
        cookieManager.removeAllCookie();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush();
        } else {
            CookieSyncManager.getInstance().sync();
        }

        if(null != InitUtils.cookieJar) {
            InitUtils.cookieJar.clear();
            InitUtils.cookieJar.clearSession();
        }
    }
}
2年前 回复