How to prevent Retrofit from clearing my cookies

You need to set a Cookie persistent Client. Since you're using Android and retrofit I suggest using OKHttp wich is better supported by retrofit and Android thread safe, the way to this is the following

//First create a new okhttpClient (this is okhttpnative)
OkHttpClient client = new OkHttpClient(); //create OKHTTPClient
//create a cookieManager so your client can be cookie persistant
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager); //finally set the cookie handler on client

//OkClient is retrofit default client, ofcourse since is based on OkHttClient
//you can decorate your existing okhttpclient with retrofit's okClient
OkClient serviceClient = new OkClient(client);

//finally set in your adapter
RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("Some eNdpoint")
            .setClient(serviceClient)
            .build();

The point of using Okhttp instead of the defaultHttpClient(by apache) is that okhttp is threadsafe for android and better supported by retrofit.

Remembar that if you create another adapter you will need to set the same client, perhaps if you implement singleton on the client instance you will use the same one for all your requests, keeping in the same context

I hope this helps,best


If you use Retrofit 2 you can add the library:

compile "com.squareup.okhttp3:okhttp-urlconnection:3.2.0"

then use the following code to manage cookies when you create your OkHttp client:

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cookieJar(new JavaNetCookieJar(cookieManager));