Maintain cookie session in Android(Retrofit)

A session is a sequence of requests made by a single end-user during a visit to a particular site. A session or query session may be all queries made by a user in a particular time period or it may also be a series of queries or navigation with a consistent underlying user need.

In Android, if we use the retrofit for web services call it internally uses OkHttp and OkHttp does not keep the track of session automatically. Generally, the session is maintained using the cookie value that we get in each response we receive.

So, we need to keep the cookie from one call to another. this can be down using CookieManager as follows:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();

CookieHandler cookieHandler = new CookieManager();
OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(interceptor)
.cookieJar(new JavaNetCookieJar(cookieHandler))
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)

Retrofit retrofit = new Retrofit.Builder()

for this following dependencies are required:

compile ‘com.squareup.okhttp3:logging-interceptor:3.4.1’
compile ‘com.squareup.okhttp3:okhttp:3.4.1’
compile ‘com.squareup.okhttp3:okhttp-urlconnection:3.6.0’

Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box