Skip to content

Instantly share code, notes, and snippets.

@nikhiljha
Created July 29, 2016 04:35
Show Gist options
  • Star 60 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save nikhiljha/52d45ca69a8415c6990d2a63f61184ff to your computer and use it in GitHub Desktop.
Save nikhiljha/52d45ca69a8415c6990d2a63f61184ff to your computer and use it in GitHub Desktop.
Retrofit2/OkHttp3 Cookies (Drag and Drop, One Size Fits 99%)
// Original written by tsuharesu
// Adapted to create a "drop it in and watch it work" approach by Nikhil Jha.
// Just add your package statement and drop it in the folder with all your other classes.
import android.content.Context;
import android.preference.PreferenceManager;
import android.util.Log;
import java.io.IOException;
import java.util.HashSet;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* This interceptor put all the Cookies in Preferences in the Request.
* Your implementation on how to get the Preferences may ary, but this will work 99% of the time.
*/
public class AddCookiesInterceptor implements Interceptor {
public static final String PREF_COOKIES = "PREF_COOKIES";
// We're storing our stuff in a database made just for cookies called PREF_COOKIES.
// I reccomend you do this, and don't change this default value.
private Context context;
public AddCookiesInterceptor(Context context) {
this.context = context;
}
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
HashSet<String> preferences = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet(PREF_COOKIES, new HashSet<String>());
// Use the following if you need everything in one line.
// Some APIs die if you do it differently.
/*String cookiestring = "";
for (String cookie : preferences) {
String[] parser = cookie.split(";");
cookiestring = cookiestring + parser[0] + "; ";
}
builder.addHeader("Cookie", cookiestring);
*/
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
}
return chain.proceed(builder.build());
}
}
// Original written by tsuharesu
// Adapted to create a "drop it in and watch it work" approach by Nikhil Jha.
// Just add your package statement and drop it in the folder with all your other classes.
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.io.IOException;
import java.util.HashSet;
import okhttp3.Interceptor;
import okhttp3.Response;
public class ReceivedCookiesInterceptor implements Interceptor {
private Context context;
public ReceivedCookiesInterceptor(Context context) {
this.context = context;
} // AddCookiesInterceptor()
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
HashSet<String> cookies = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet("PREF_COOKIES", new HashSet<String>());
for (String header : originalResponse.headers("Set-Cookie")) {
cookies.add(header);
}
SharedPreferences.Editor memes = PreferenceManager.getDefaultSharedPreferences(context).edit();
memes.putStringSet("PREF_COOKIES", cookies).apply();
memes.commit();
}
return originalResponse;
}
}
// By Nikhil Jha
// License MIT
// DON'T ADD THIS FILE TO YOUR OTHER CLASSES
// THIS IS AN EXAMPLE TO TEACH YOU HOW TO MAKE REQUESTS WITH THE MAGIC COOKIES
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new AddCookiesInterceptor(context)); // VERY VERY IMPORTANT
builder.addInterceptor(new ReceivedCookiesInterceptor(context)); // VERY VERY IMPORTANT
client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("my-base") // REQUIRED
.client(client) // VERY VERY IMPORTANT
.addConverterFactory(GsonConverterFactory.create())
.build(); // REQUIRED
Your.ThingyClass = retrofit.create(Your.ThingyClass.class);
Call<...> call = yourclass.somecall(new yourclass(example, example));
@dabitdev
Copy link

@makiabuan the interceptors needs to be added once in the http client. Make sure that all requests are using the same okhttp client.
You do not need to call anything. The interceptor does the work by itself.

@congtieniuh
Copy link

Thank you very much, This work for me.

@mustaphamichael
Copy link

Lifesaver !! Thank you.

@banmarkovic
Copy link

Anyone has problem on Android Pie with these interceptors? It seems that they are not triggered on Android 9, on other versions it works perfectly..

@banmarkovic
Copy link

It seems that the problem was in CertificateFactory.getInstance("X.509", "BC"), X.509 is not found for Android 9. CertificateFactory.getInstance("X509") is the fix.

@sandeepGLS
Copy link

sandeepGLS commented May 29, 2019

Thanks, Worked for me

@dileep57
Copy link

Thanks Bro, its working.. :)

@Sourav242
Copy link

Great help. Thanks Bro.

@aqibshxhzd
Copy link

yo bro thanks ,,, its working, you saved my ass :D

@Dilmurod724
Copy link

Great help. Thanks

@murraygunn
Copy link

I'm using hilt and am struggling to make 'context' available. Any suggestions?

@murraygunn
Copy link

I got it. My problem was trying to use @ApplicationContext as is (@ApplicationContext context: ApplicationContext). It works fine if you leave it as Context (@ApplicationContext context: Context)

I've pulled everything together for a Hilt-based solution at https://stackoverflow.com/questions/67950681/using-cookies-with-retrofit-and-hilt-and-recommended-architecture

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