【问题标题】:Persistent Cookie Storing with HTTPUrlConnection使用 HTTPUrlConnection 进行持久性 Cookie 存储
【发布时间】:2020-09-22 14:21:08
【问题描述】:

我目前正在开发一个应用程序,其主要目的是让一个人登录,然后向那个人显示一些信息。

我正在使用 HttpUrlConnection 发送和接收来自网站的输入。

由于该应用程序主要面向 Web,因此我需要确保用户即使在关闭应用程序后仍能保持登录状态,这意味着我需要以某种方式保存会话 Cookie。

我读过 CookieManager 和 CookieStore,但是,它们不适合这个,因为它们只在应用程序打开时存储 cookie,一旦应用程序关闭它们就会丢失所有信息。

什么是在设备上永久存储会话 cookie 的安全且安全的好方法?

【问题讨论】:

    标签: android http cookies


    【解决方案1】:

    您可以使用 SharedPreferences。即使您的应用程序打开和关闭,它也可以将数据保留在此处。您以后可以轻松获得它。您可以查看下面的 here SharedPreferences 示例代码。

    SharedPreferences sp;
    sp = getSharedPreferences("sampleName",MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("key", "value");
    editor.commit();
    

    还有另一种方法可以解决这个问题。您可以写入文件并在需要时读取它们。下面的示例代码用于解决方案。并且您可以查看here

    public static void writeStringAsFile(final String fileContents, String fileName) {
        Context context = App.instance.getApplicationContext();
        try {
            FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
            out.write(fileContents);
            out.close();
        } catch (IOException e) {
            Logger.logError(TAG, e);
        }  
    }
    public static String readFileAsString (String fileName) {
    
        Context context = App.instance.getApplicationContext();
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        BufferedReader in = null;
    
        try {
            in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
            while ((line = in.readLine()) != null) stringBuilder.append(line);
    
        } catch (FileNotFoundException e) {
            Logger.logError(TAG, e);
        } catch (IOException e) {
            Logger.logError(TAG, e);
        } 
    
        return stringBuilder.toString();
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 SharedPreferences 保存 cookie。它是android中最常用的框架来简单地存储key:value数据。

      【讨论】:

        猜你喜欢
        • 2015-12-09
        • 2017-07-25
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-22
        • 2014-10-07
        相关资源
        最近更新 更多