篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用Okhttp框架登录之后的Cookie设置到webView中(转)相关的知识,希望对你有一定的参考价值。
- @SuppressWarnings("deprecation")
- public void synCookies(Context context, String url) {
- CookieSyncManager.createInstance(context);
- CookieManager cookieManager = CookieManager.getInstance();
- cookieManager.setAcceptCookie(true);
-
-
- cookieManager.removeAllCookie();
-
-
-
-
-
- List<Cookie> cookies=SimpleCookieJar.getCookies();
-
-
-
- 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++) {
- Log.d("cookie[i]",cookie[i]);
- cookieManager.setCookie(url, cookie[i]);
- }
-
-
- CookieSyncManager.getInstance().sync();
- }
2.SimpleCookieJar 这个类中设置:
- import java.util.ArrayList;
- import java.util.List;
- import okhttp3.Cookie;
- import okhttp3.CookieJar;
- import okhttp3.HttpUrl;
- public final class SimpleCookieJar implements CookieJar
- {
- private final List<Cookie> allCookies = new ArrayList<Cookie>();
-
-
-
- private static List<Cookie> cookies;
-
- public static List<Cookie> getCookies() {
- return cookies != null ? cookies : new ArrayList<Cookie>();
- }
-
- public static void setCookies(List<Cookie> cookies) {
- SimpleCookieJar.cookies = cookies;
- }
-
- public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies)
- {
- allCookies.addAll(cookies);
-
- setCookies(cookies);
- }
-
-
- @Override
- public synchronized List<okhttp3.Cookie> loadForRequest(HttpUrl url)
- {
- List<Cookie> result = new ArrayList<Cookie>();
- for (Cookie cookie : allCookies)
- {
- if (cookie.matches(url))
- {
- result.add(cookie);
- }
- }
- return result;
- }
- }