7

Can anyone please suggest me a way to manage cookies in robospice retrofit type HTTP requests.

I have a authentication system which has a login , a few GET HTTP requests , and a logout.

During login i need to save the session and use the same session for the rest GET HTTP requests and when I logout the session has to be cleared.

Here the login is a HTTP POST request which sends and recieves data through JSON format. I am using robospice retrofit as it easily manages the login and logout requests.

Revanth Gopi
  • 350
  • 4
  • 14

1 Answers1

7

You can set system-wide cookie-handler via java.net.CookieManager

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);

in your custom Application class.

To clear cookies after logout you can use method like this

public void clearCookies() {
    cookieManager.getCookieStore().removeAll();
}
colriot
  • 1,978
  • 1
  • 14
  • 21
  • It works only for API >= 9 right ? I need the support for Android API 8 also – Revanth Gopi Jun 29 '14 at 08:53
  • @RevanthGopi yeah, that's right. You can check API level at runtime (as Retrofit does) and work with `java.net.CookieManager`'s cookie management for API >= 9, and with Apache's `BasicCookieStore` for API < 9. See this question for one possible way of using `BasicCookieStore`: http://stackoverflow.com/questions/18894540/using-retrofit-with-cookie-persistence – colriot Jun 29 '14 at 09:38