Skip to content

Instantly share code, notes, and snippets.

@tsuharesu
Last active June 8, 2024 07:30
Show Gist options
  • 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());
@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