OkHttp3 Cookie持久化

时间:2016-08-26 15:37:34

标签: cookies okhttp3

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

当我使用okhttp3创建cookie持久性时,有一个例外:

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

很多人都说是因为并发hashmap的JDK1.8版本返回值,但我不知道如何解决。我的JDK版本是1.8。

1 个答案:

答案 0 :(得分:0)

您的add方法对Cookie Map有两个非null安全调用。我想只需编辑这两行就可以使用safe get方法或使用null检查。

自:

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

致:

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

此行也

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