【问题标题】:How to store a Cookie as persistent data?如何将 Cookie 存储为持久数据?
【发布时间】:2012-12-01 04:11:02
【问题描述】:

当连接到服务器时,我得到 Cookies 并将它们存储在一个列表中。

稍后在建立连接时,我将这些 cookie 添加到 DefaultHttpClient。

问题是,当应用程序处于后台一段时间时,所有类数据都将丢失,包括 DefaultHttpClient

因此我丢失了 cookie

有没有办法让 DefaultHttpClient 永远活着?

或者有什么更好的方式来存储和使用cookies?

谢谢

【问题讨论】:

    标签: android cookies httpclient


    【解决方案1】:

    从 cookie 中获取它,然后在应用程序被终止时将其保存在共享首选项中(例如 onStop 方法)。然后在 onCreate() 上重新加载它。类似的东西:

    public class Calc extends Activity {
       public static final String PREFS_NAME = "MyPrefsFile";
    
       @Override
       protected void onCreate(Bundle state){
          super.onCreate(state);
          . . .
    
          // Restore preferences
          SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
          String silent = settings.getString("cookie", null);
          if(cookie == null) {
              // first time, get cookie again and save it
          } else {
              // set cookie manually for HTTPClient
          }
       }
    
       @Override
       protected void onStop(){
          super.onStop();
    
         // We need an Editor object to make preference changes.
         // All objects are from android.context.Context
         SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
         SharedPreferences.Editor editor = settings.edit();
         editor.putString("cookie", theCookie);
    
         // Commit the edits!
         editor.commit();
       }
    }
    

    (我省略了获取和设置cookie的代码,我认为这不是问题)

    【讨论】:

    • cookie 可以作为字符串存储在 sharedPreferences 中吗?在重用它的同时,我必须将它转换为 (Cookie)??
    • cookie VALUE 是一个字符串,你可以保存它。这是您重新创建 Cookie 集时唯一需要知道的事情。
    • 使用 BasicClientCookie("name", "value")BasicHttpContext()
    • 同时使用 PersistentCookieStore 会自动完成这一切吗??
    猜你喜欢
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多