Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handle Cookies easily with Retrofit/OkHttp
/**
* This interceptor put all the Cookies in Preferences in the Request.
* Your implementation on how to get the Preferences MAY VARY.
* <p>
* Created by tsuharesu on 4/1/15.
*/
public class AddCookiesInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
HashSet<String> preferences = (HashSet) Preferences.getDefaultPreferences().getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
}
return chain.proceed(builder.build());
}
}
/**
* This Interceptor add all received Cookies to the app DefaultPreferences.
* Your implementation on how to save the Cookies on the Preferences MAY VARY.
* <p>
* Created by tsuharesu on 4/1/15.
*/
public class ReceivedCookiesInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
HashSet<String> cookies = new HashSet<>();
for (String header : originalResponse.headers("Set-Cookie")) {
cookies.add(header);
}
Preferences.getDefaultPreferences().edit()
.putStringSet(Preferences.PREF_COOKIES, cookies)
.apply();
}
return originalResponse;
}
}
/**
* Somewhere you create a new OkHttpClient and use it on all your requests.
*/
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new AddCookiesInterceptor());
okHttpClient.interceptors().add(new ReceivedCookiesInterceptor());
@antoniomerlin

This comment has been minimized.

Copy link

antoniomerlin commented Jan 10, 2016

Hey please can u provide an overall to how to implement this in singleton way.

@tsuharesu

This comment has been minimized.

Copy link
Owner Author

tsuharesu commented Apr 17, 2016

Look elsewhere on how to use as a singleton. I use Dagger to inject my OkHttpClient, for example.

@marcinOz

This comment has been minimized.

Copy link

marcinOz commented Apr 19, 2016

with lib 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0' it as simple as just add
JavaNetCookieJar jncj = new JavaNetCookieJar(CookieHandler.getDefault());
OkHttpClient.Builder()
.cookieJar(jncj)
.build();

@Shilaghae

This comment has been minimized.

Copy link

Shilaghae commented Apr 26, 2016

I had some problems with this implementation, because you send back the cookies exactly as you get them, but it can append that there are more cookies with the same name, in my case the server sent me two phpsessid and it ended up with Unauthorized user. We need a cookie manager so marcinOz implementation is more accurate. And I would add that this is also for older version of okhttp-urlconnection.

@MrThiago

This comment has been minimized.

Copy link

MrThiago commented May 25, 2016

This works create. Thanks buddy.

@ramesh-anandhan

This comment has been minimized.

Copy link

ramesh-anandhan commented Jul 14, 2016

Thanks

@nikhiljha

This comment has been minimized.

Copy link

nikhiljha commented Jul 29, 2016

https://gist.github.com/nikhiljha/52d45ca69a8415c6990d2a63f61184ff

I made a one size fits all, drag and drop approach based off of your gist.

This will "just work" and shouldn't require any work on your part (I hope).

Enjoy!

@justinging

This comment has been minimized.

Copy link

justinging commented Aug 1, 2016

Thank you nikhiliha & tsuharesu
Your code saved my day

Thanks!

@AItsuki

This comment has been minimized.

Copy link

AItsuki commented Aug 15, 2016

cool

@khrlimam

This comment has been minimized.

Copy link

khrlimam commented Nov 12, 2016

is that means the app runs without worrying statefull web app sessions?

@gewuxy

This comment has been minimized.

Copy link

gewuxy commented Feb 24, 2017

for (String cookie : preferences) { builder.addHeader("Cookie", cookie); Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp }
so a request has multi Cookie ?

@piscessu

This comment has been minimized.

Copy link

piscessu commented May 9, 2017

cool thanks

@GaneshShetty951

This comment has been minimized.

Copy link

GaneshShetty951 commented May 18, 2017

Hey bro session id getting refreshed again and again what might be the reason. ?

@arvi

This comment has been minimized.

Copy link

arvi commented May 30, 2017

Thank you so muuuuuch! For some reason, answer from SO https://stackoverflow.com/a/36865953/2098493 didn't work for me and also https://github.com/franmontiel/PersistentCookieJar.

Your solution persists server request cookie even if app is destroyed! :) I'm so happy. Finally found the right one.

@gotev

This comment has been minimized.

Copy link

gotev commented Jan 3, 2018

Kotlin version with helper methods to create OkHttp client and Retrofit instance: https://gist.github.com/nikhiljha/52d45ca69a8415c6990d2a63f61184ff#gistcomment-2310417

@Yexingshuai

This comment has been minimized.

Copy link

Yexingshuai commented Aug 9, 2018

Thank

@PeterDasondhi

This comment has been minimized.

Copy link

PeterDasondhi commented Sep 8, 2018

@arvi can you please let me know how can you do that. persists server request cookie even if app is destroyed!. This one

@CaesarBourne

This comment has been minimized.

Copy link

CaesarBourne commented Oct 25, 2018

Please the cookies are of which type e.g strings e.t.c cos i need that to create a custom response for retrofit

@akshay-testpress

This comment has been minimized.

Copy link

akshay-testpress commented Apr 11, 2019

How to get url in AddCookiesInterceptor

@SimbaMupfu

This comment has been minimized.

Copy link

SimbaMupfu commented Jul 8, 2019

Thanks

@manimaran96

This comment has been minimized.

Copy link

manimaran96 commented Oct 13, 2019

I used above steps to store the cookie then add on request.
Worked on actively on login and continue use.
But once close and open the app not worked.
(Once restart the comes CSRF token invalid issue.)

https://github.com/manimaran96/Spell4Wiki/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.