Android:如何存储 cookie? [英] Android: How to store cookies?

查看:16
本文介绍了Android:如何存储 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Android 应用程序中,每个 Activity 都填充了来自网络某处的 xml 文件的数据.提供这些文件的网站具有使用 cookie 的登录机制.

In my Android app, each activity is filled with data from an xml file which is somewhere on the web. The website providing these files has a login mechanism, that works with cookies.

我知道如何向登录页面发出 HTTP 请求并接收 cookie.我不知道的是,我如何存储它以在其他活动以及下次启动应用程序时重新使用它.该 cookie 的有效期为一年,因此我的应用的用户应该登录一次,然后一整年都不要再次登录.

I know how to make a HTTP Request to the login page and receive a cookie. What I don't know is, how I can store it to re-use it in both other activities AND when the app is started the next time. The cookie is valid for a year, so the user of my app should log in once and then never again for a whole year.

我该怎么做?我用谷歌搜索了很多,但要么我使用了错误的关键字,要么互联网上没有简单的解决方案.我希望这里有人可以帮助我.

How do I do that? I googled a lot, but either I used the wrong keywords or there are no simple solutions on the internet. I hope somebody here can help me.

提前致以最好的问候和感谢,Jan Oliver

Best regards and thanks in advance, Jan Oliver

推荐答案

看起来 Android 正在使用默认的内存实现,因此您需要创建自己的持久性 cookie 存储.

It looks like Android is using the default in memory implementation so you will need to create your own persistent cookie store.

本 Java 教程概述了利用默认实现创建您自己的持久存储.http://download.oracle.com/javase/tutorial/networking/cookies/custom.html

This Java Tutorial outlines creating your own persistent store taking advantage of the default implementation. http://download.oracle.com/javase/tutorial/networking/cookies/custom.html

该示例有两个用于存储(读/写)的待办事项.对于存储,我将仅使用 SharedPreferences 来存储您需要的会话 cookie,而不保留任何其他 cookie.

The sample has two todo's for storage (read/write) For storage I would just use SharedPreferences to store just the session cookie that you need and not persist any others.

该示例使用了一个关闭钩子,这不是您在 Android 中想要的.代替 run() 和钩子,我只需要一个新的公共方法 persist() 来保存您想要的内容,尽管这需要您手动 persist() 存储.

The sample uses a shutdown hook which is not what you want in Android. In place of run() and the hook I would just have a new public method persist() that saves what you want, though that requires that you persist() the store by hand.

鉴于您只有一两个重要的 cookie,您可以将它们保存在 add(...)

Given that you only have one or two cookies that matter you could save them in the add(...)

这篇关于Android:如何存储 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆