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.
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.
Best regards and thanks in advance, Jan Oliver
On your Android phone or tablet, open the Chrome app. Tap More button, marked as three dots, and then Settings, found at the top-right corner of the web page. Tap Site settings and then Cookies.
WebViews automatically persist cookies into a android. webkit. CookieManager. Need to store cookies from a WebView into a java.
Use a CookieSyncManager to store your cookie value. It can persist across application starts.
Beware of using CookieSyncManager inside of WebViewClient#shouldInterceptRequest on KitKat. It will deadlock.
EDIT
CookieSyncManager
was deprecated in API 21:
This class was deprecated in API level 21. The WebView now automatically syncs cookies as necessary. You no longer need to create or use the CookieSyncManager. To manually force a sync you can use the CookieManager method flush() which is a synchronous replacement for sync().
It looks like Android is using the default in memory implementation so you will need to create your own persistent cookie store.
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
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.
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.
Given that you only have one or two cookies that matter you could save them in the add(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With