0
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持久性,有一個例外:OkHttp3 Cookie的持久性
NullPointerException: Attempt to invoke virtual method 'java.util.Set java.util.concurrent.ConcurrentHashMap.keySet()' on a null object reference
很多人說這是因爲ConcurrentHashMap的返回值的JDK1.8版本,但我不知道如何解決。我的JDK版本是1.8。