2016-08-26 146 views
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。

回答

0

您的add方法對cookie Map有兩個非null安全調用。我認爲只需編輯這兩行以使用安全get方法或使用空值檢查。

來源:

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()));