Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android CookieManager setCookie doesn't set anything

in my application, I'm getting two cookies from an HttpGet request and store them in the CookieManager like this:

//Clear old cookies
CookieManager.getInstance().removeAllCookie();
CookieSyncManager.getInstance().sync();

//Save the two cookies: auth token and session info
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
        String cookieString = cookie.getName() + "=" + cookie.getValue() + "; Domain=" + cookie.getDomain();
        CookieManager.getInstance().setCookie("http://alpha.mydomainname.com", cookieString);
    }

    System.out.println(CookieManager.getInstance().hasCookies()); //Prints false in 2.3,  true in 4.0.3

    CookieSyncManager.getInstance().sync();

    System.out.println(CookieManager.getInstance().hasCookies()); //Also prints false in 2.3 and true in 4.0.3
}

I'm testing the same code in two different devices and the funny thing is, the cookies are set (and also transferred between launches of the application) correctly in 4.0.3 but not in 2.3.3. When I say they are not set, I mean that hasCookies() returns false and also getCookie() returns null when I provide the URL.

I've tried every possible combination for the Cookie URL when calling setCookie: "http://alpha.mydomainname.com", "http://www.mydomainname.com", "http://mydomainname.com", "mydomainname.com", "alpha.mydomainname.com", ".mydomainname.com", "www.mydomainname.com", none of them works. Please help.

like image 563
Ayberk Özgür Avatar asked Jul 28 '12 10:07

Ayberk Özgür


Video Answer


1 Answers

I recently had a similar problem, and the following solution worked for me. I create/get instances of CookieSyncManager and CookieManager at the beginning, and use them throughout the code, instead of creating new instances again. I also had to experiment with setting the cookie on the correct domain - I had to set it to the domain that appears in one of the redirects.

final CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
final CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();

//Save the two cookies: auth token and session info
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
        String cookieString = cookie.getName() + "=" + cookie.getValue() + "; Domain=" + cookie.getDomain();
        cookieManager.setCookie("http://mydomainname.com", cookieString);
    }
    cookieSyncManager.sync();
}
like image 120
synapseError Avatar answered Oct 01 '22 09:10

synapseError