10

I guys, I'm using retrofit and I wonder how to transparently handle the session cookie. For that I extend the given ApacheClient and use a CookieStore in the custom call to ApacheClient.execute(HttpClient, HttpUriRequest) :

Client client = new ApacheClient() {
    final CookieStore cookieStore = new BasicCookieStore();
    @Override
    protected HttpResponse execute(HttpClient client, HttpUriRequest request) throws IOException {
        // BasicHttpContext is not thread safe 
        // CookieStore is thread safe
        BasicHttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        return client.execute(request, httpContext);
    }
};

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer(API_URL)
    .setClient(client)
    .build();

Is there a better way to do this with the build-in retrofit API (with no HttpClient extension) ?

avianey
  • 5,545
  • 3
  • 37
  • 60

1 Answers1

13

Starting from API 9 you have java.net.CookieManager and can set system-wide cookie handler like this:

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

Yes, Apache Http client uses its own cookie-handling mechanism. But it should not be the problem because starting from API 9 HttpURLConnection is recommended HTTP client. If you use Retrofit from Square you may also like their OkHttp lib - custom URLConnection implementation with lots of useful capabilities.

colriot
  • 1,978
  • 1
  • 14
  • 21
  • Can you use this with retrofit, If I call this, on my login fragment, can I expect every call made from retrofit to automatically have the cookie attached? – Lion789 Mar 15 '14 at 22:05
  • 2
    @Lion789 yes, you can. But it's better to place this code into your custom `Application` successor. – colriot Mar 17 '14 at 06:42
  • by application successor what are you referring to exactly? i.e. this is what I was trying to do...http://stackoverflow.com/questions/22425993/how-to-retrieve-cookies-in-android-retrofit --- also, for the accept_all is it better to let it be the default only the original server or that will not let me get the cookie and if it does, then do I need to do anything extra, because from what I understand I can leave that line out since it is defaulted to that? – Lion789 Mar 17 '14 at 07:50
  • @Lion789 I mean subclass of `Application` class. For example, in its `onCreate` method. – colriot Mar 24 '14 at 08:38
  • 1
    This worked for me, apparently without this OkHttp won't save any cookies that are requested to be set by the server(Set-Cookie header), but you need to remember to use one single http client instance, I solved that using Singleton with the help of dagger. – Davi Alves May 11 '14 at 06:49
  • Does this persist cookies across app restarts? – hitmaneidos May 26 '16 at 10:57