Skip to content

Instantly share code, notes, and snippets.

@quevon24
Forked from tsuharesu/AddCookiesInterceptor.java
Created December 19, 2017 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quevon24/e4ebed276d192fa4c2b2943f0a3a777a to your computer and use it in GitHub Desktop.
Save quevon24/e4ebed276d192fa4c2b2943f0a3a777a 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());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment