【问题标题】:Restore cookies in onResume() Android app?在 onResume() Android 应用程序中恢复 cookie?
【发布时间】: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 时做错了什么。

我做错了什么?

希望任何人都可以提供帮助,在此先感谢。

【问题讨论】:

    标签: android cookies


    【解决方案1】:

    您也可以使用android-async-http,它是一个非常强大的灵活的Android http 客户端。

    根据其文档,您可以轻松地在您的 android 应用程序中使用 cookie:

    首先,创建一个 AsyncHttpClient 的实例:

    AsyncHttpClient myClient = new AsyncHttpClient();
    

    现在将此客户端的 cookie 存储设置为 PersistentCookieStore 的新实例,由 Activity 或应用程序上下文构造(通常这就足够了):

    PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
    myClient.setCookieStore(myCookieStore);
    

    从服务器接收到的任何 cookie 现在都将存储在持久性 cookie 存储中。

    要将您自己的 cookie 添加到存储中,只需构造一个新的 cookie 并调用 addCookie:

    BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
    newCookie.setVersion(1);
    newCookie.setDomain("mydomain.com");
    newCookie.setPath("/");
    myCookieStore.addCookie(newCookie);
    

    祝你好运。

    【讨论】:

    • 感谢您的回答。我是否应该为我的每个请求都有一个 AsyncHttpClient 实例?我必须在几个活动中做几个请求。我必须每次都在新客户端上创建吗?
    • 您可以有多个 async-http-clients,但最佳做法是通过在 Application 类或单例类中创建一个实例来提供一个实例。
    • 知道了。你知道有什么好的 AsyncHttpClient 教程吗?我真的不知道如何开始,因为我必须更改所有应用程序才能使用该库。
    • its documentation 非常简单。您只需创建一个 http 客户端。然后调用 http-client 的 get 或 'post` 或 'put` 方法,并将响应回调传递给该方法。
    • 好的,谢谢。还有一个问题,即使 Activity 暂停,PersistentCookieStore 的实例还会有它的数据吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多