由于某种原因,当我打开相机意图并从中返回时,CookieManager有时会丢失会话变量。这不会一直发生,但确实经常发生。我可以确认会话变量正在丢失,因为我的后端Web服务器正在抱怨它。
这是我在MainApplication上的代码,在onCreate()方法中扩展了Application类。
CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
如果有人能让我对正在发生的事情有所了解,我将不胜感激。
更新
我尝试使用以下代码存储Cookie,但它不起作用!
public static void GetCookies(Context context){
SharedPreferences prefs = QuickFunctions.getPreferences(context);
CookieManager ckManager = (CookieManager) CookieHandler.getDefault();
CookieStore ckStore = ckManager.getCookieStore();
List<URI> uriList=ckStore.getURIs();
List<HttpCookie> cks = ckStore.getCookies();
boolean sessionExists=false;
for (URI uri : uriList) {
if (uri.getHost().contains("testsite.ca")){
sessionExists=true;
}
}
if (sessionExists==false){
if (prefs.contains("sessionURI") && prefs.contains("cookieName") && prefs.contains("cookieValue")){
URI intuchURI = URI.create(prefs.getString("sessionURI", "defaultString"));
HttpCookie ck = new HttpCookie( prefs.getString("cookieName", "defaultString"), prefs.getString("cookieValue", "defaultString"));
ckStore.add(intuchURI,ck);
}
}
}
public static void SaveCookies(Context context){
SharedPreferences prefs = QuickFunctions.getPreferences(context);
Editor edit=prefs.edit();
CookieManager ckManager = (CookieManager) CookieHandler.getDefault();
CookieStore ckStore = ckManager.getCookieStore();
List<URI> uriList=ckStore.getURIs();
for (URI uri : uriList) {
if (uri.getHost().contains("testsite.ca")){
edit.putString("sessionURI", uri.toString());
List<HttpCookie> cks = ckStore.get(uri);
for (HttpCookie ck : cks) {
if (ck.toString().contains("sessionid")){
edit.putString("cookieName",ck.getName());
edit.putString("cookieValue",ck.getValue());
}
}
}
}
edit.commit();
}
谢谢!