简体   繁体   English

OkHttp3 Cookie持久

[英]OkHttp3 Cookie Persistent

public void add(HttpUrl url, Cookie cookie) {
    String name = getCookieToken(cookie);

    //将cookies缓存到内存中 如果缓存过期 就重置此cookie
    if (!cookie.persistent()) {
        if (!cookies.containsKey(url.host())) {
            cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
        }
        cookies.get(url.host()).put(name, cookie);
    } else {
        if (cookies.containsKey(url.host())) {
            cookies.get(url.host()).remove(name);
        }
    }

    LogUtil.e("Cookie:" + cookies.get(url.host()).keySet().toString());
    //讲cookies持久化到本地
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
    prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
    prefsWriter.apply();
}

public List<Cookie> get(HttpUrl url) {
    ArrayList<Cookie> ret = new ArrayList<>();
    if (cookies.containsKey(url.host()))
        ret.addAll(cookies.get(url.host()).values());
    return ret;
}

When I used okhttp3 to create a cookie persistence, there was an exception: 当我使用okhttp3创建cookie持久性时,出现了一个例外:

NullPointerException: Attempt to invoke virtual method 'java.util.Set java.util.concurrent.ConcurrentHashMap.keySet()' on a null object reference

Many people say that it is because of the JDK1.8 version of the concurrenthashmap return value, but I do not know how to solve.My JDK version is 1.8. 很多人说这是因为并发哈希映射的返回值是JDK1.8版本,但是我不知道该怎么解决。我的JDK版本是1.8。

Your add method has two non null safe calls to the cookies Map. 您的add方法具有对Cookie Map的两个非null安全调用。 I think just edit these two lines to use the safe get method or use null checks. 我认为只需编辑这两行即可使用安全的get方法或使用null检查。

From: 从:

LogUtil.e("Cookie:" + cookies.get(url.host()).keySet().toString());

To: 至:

if (cookies.containsKey(url.host())) 
  LogUtil.e("Cookie:" + cookies.get(url.host()).keySet().toString());

and this line also 这条线也

prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM