Java android – CookieHandler – How do I keep cookies after closing the application? … here is a solution to the problem.
Java android – CookieHandler – How do I keep cookies after closing the application?
To persist cookies after each request in HttpURLConnection, you should add CookieHandler: on the application you start
with
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
But when the application closes and opens again, the cookies are empty …
So how are cookies stored after closing?
For example, save them in a SharedPreferences or file and retrieve them after opening….
I tried to get them to use the CookieStore, but that didn’t work :….
Save:
Settings.Save(c, TAG, cookieManager.getCookieStore().getCookies().toString());
Load:
String load = Settings.Load(c, TAG);
if (load != null) {
for (HttpCookie hc : HttpCookie.parse(load)) {
cookieManager.getCookieStore().add(new URI(Data.domain), hc);
}
}
Thanks…
Solution
The default CookieStore
does not save anything to disk, you need to implement one that can be saved. This is an example implementation saves cookies directly to SharedPreferences.