Add Cookies Interceptor Using Retrofit In Android

Hi guys today i am going to share a workaround to create a cookie handler or cookies intercepter with retrofit on android.

Before some days ago i noticed that by default retrofit does’t use cookies mechanism while calling a web service when i tried to call restfull API created with Laravel server.

Laravel server usages cookies to identify request and maintains session by verifiying cookies which it sends or creates when first call is made to access laravel resources.

Browsers do it very well with cookies handling. So when i have found some mishappening with API calls not getting response from laravel server from Android using Retrofit framework then i digged into the problem and found cookies were not being sent. So i decided to create a Cookies Handler and Integrated with Retrofit.

There is an important thing to be remembered while handling Cookies – First we have to store cookies returned within response from server call and when we are makig another call we should have to add with request.

To achieve this we can use sharedPrefrences storage provided by anddroid OS.

1. You have to create ReceivedCookiesInterceptor to intercept and save Cookies

2. And another AddCookiesInterceptor to add recived cookies in subsequesnt calls.

3. Now its time to register above Interceptors with Retrofit

4. I have used two static methods created inside Methods class

5. You need to add dependencies in your app level build.gradle file

Hope this will help you a lot and thanks for reading this artical.

Categories: Android,Retrofit

Tags: ,

2 Comments

Leave A Reply

Your email address will not be published.