7

I want to logout my twitter account by deleting the cookies created by it. I am able to retrive the cookies created by twitter using code:

String twit_cookie = getCookie ("http://www.twitter.com");

But how can i delete only cookies created by twitter because removeAllCookie() deletes all the cookies created by browser. How can i delete the specific cookie by URL or by name???

Please help...

Rajat
  • 1,378
  • 4
  • 17
  • 33
  • 3
    Checkout the answers here: http://stackoverflow.com/questions/2834180/how-to-remove-cookies-using-cookiemanager-for-a-specific-domain – Steve Tauber Aug 09 '14 at 00:03

2 Answers2

3

CookieManager class has a method setCookie. Have you tried it like:

setCookie("http://www.twitter.com", null);

Or perhaps

setCookie("http://www.twitter.com", "auth_token=''");
Simas
  • 43,548
  • 10
  • 88
  • 116
3

You can use the method CookieManager#setCookie(String url, String value). As stated in the docs:

Sets a cookie for the given URL. Any existing cookie with the same host, path and name will be replaced with the new cookie.

The "clearest" way is to set all cookies created by twitter to expired (a time in the past). The code from this answer is almost right, except the date is in the future.
Modified code:

final String domain = "http://www.twitter.com";
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
String cookiestring = cookieManager.getCookie(domain); //get all cookies
String[] cookies =  cookiestring.split(";");
for (int i=0; i<cookies.length; i++) {
    String[] cookieparts = cookies[i].split("="); //split cookie into name and value etc.
    // set cookie to an expired date
    cookieManager.setCookie(domain, cookieparts[0].trim()+"=; Expires=Wed, 31 Dec 2000 23:59:59 GMT");
}
CookieSyncManager.getInstance().sync(); //sync the new cookies just to be sure
Community
  • 1
  • 1
Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
  • What about this ? " The cookie being set must not have expired and must not be a session cookie, otherwise it will be ignored." http://developer.android.com/reference/android/webkit/CookieManager.html#setCookie(java.lang.String, java.lang.String) – trante Aug 15 '14 at 18:06
  • @trante [This answer](http://stackoverflow.com/a/11621738/2829009) says that the docs are wrong and it works with expired cookies. If it doesn't work, just set the cookies to some a time some seconds in the future, so that it is valid but expires after a short time. – Manuel Allenspach Aug 16 '14 at 08:57