Skip to content

Instantly share code, notes, and snippets.

@tsuharesu
Last active April 11, 2024 12:37
Show Gist options
  • Star 96 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save tsuharesu/cbfd8f02d46498b01f1b to your computer and use it in GitHub Desktop.
Save tsuharesu/cbfd8f02d46498b01f1b to your computer and use it in GitHub Desktop.
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
Copy link

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

@tsuharesu
Copy link
Author

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

@marcinOz
Copy link

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
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
Copy link

This works create. Thanks buddy.

@ramesh-anandhan
Copy link

Thanks

@nikhiljha
Copy link

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!

@lok-27
Copy link

lok-27 commented Aug 1, 2016

Thank you nikhiliha & tsuharesu
Your code saved my day

Thanks!

@aitsuki
Copy link

aitsuki commented Aug 15, 2016

cool

@khrlimam
Copy link

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

@gewuxy
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
Copy link

piscessu commented May 9, 2017

cool thanks

@GaneshShetty951
Copy link

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

@arvi
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
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
Copy link

Thank

@PeterDasondhi
Copy link

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

@CaesarBourne
Copy link

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
Copy link

How to get url in AddCookiesInterceptor

@SimbaMupfu
Copy link

Thanks

@manimaran96
Copy link

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/

@antonsheva
Copy link

It really works. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment