【发布时间】:2014-08-15 01:21:25
【问题描述】:
我正在尝试在我的 Android 应用中维护用户会话。我的登录是这样工作的:我向 API 发出 请求 并发送用户电子邮件和密码,如果用户确实存在,那么我会得到一个 JSONObject 并使用 GSON 对其进行管理。这工作得很好。我还将 cookie 放入 CoookieStore 并将它们保存到 SharedPreferences
问题是,每次应用暂停时,我显然都丢失了 cookie,并且我无法向 API 发出任何其他请求,因为当然,我没有获得授权。
有什么方法可以在 onResume() 方法中从 SharedPreferences 恢复 cookie?
我试过了,像这样:
InteractionManager 是我管理与发出请求和从 API 获取响应有关的所有内容的类
所以在我的活动中我这样做了:
@Override
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
//Create a new instance of cookieStore to set it
//into the InteractionManager CookieStore when
//the app gets resumed.
CookieStore cookieStore = new BasicCookieStore();
String name = "user_credentials";
String value = prefs.getString(name, "");
Cookie cookie = new BasicClientCookie(name, value);
cookieStore.addCookie(cookie);
name = "user_class";
value = prefs.getString(name, "");
Log.d(TAG, "user_class cookie: " + value);
cookie = new BasicClientCookie(name, value);
interactionManager.setCookieStore(cookieStore);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
interactionManager.setLocalContext(localContext);
}
但显然我做得不对,因为 API 一直说我没有被授权,这可能是因为我在管理 cookie 时做错了什么。
我做错了什么?
希望任何人都可以提供帮助,在此先感谢。
【问题讨论】: