Java android - CookieHandler - How to keep cookies after closing the app?
Asked Answered
E

1

5

To keep cookies after each request in HttpURLConnection, should to add CookieHandler on the app starting:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

But in the app closing and opening again the cookies are empty... So how to save the cookies after the closing?

Something like save them in the SharedPreferences or in the file and get them back after the opening...

I tryed to keep them using CookieStore, but that's not worked:...

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..

Expressage answered 17/7, 2015 at 11:35 Comment(2)
Yeah, what's wrong with a sharedPreference? They perfectly fit your requirementMcmurray
Yes, but how to convert cookies to string and back? but this is no matter, I already got the answer ...Expressage
G
9

The default CookieStore does not persist anything to disk, you need to implement one which does. Here is an example implementation which saves Cookies directly to SharedPreferences.

Groundnut answered 17/7, 2015 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.