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();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

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)
.build();

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();

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’