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());
@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