Automatic cookie handling with OkHttp 3
If you want to use the new OkHttp 3 CookieJar and get rid of the okhttp-urlconnection
dependency you can use this PersistentCookieJar.
You only need to create an instance of PersistentCookieJar
and then just pass it to the OkHttp
builder:
CookieJar cookieJar =
new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(cookieJar)
.build();
Here you have a simple approach to create your own CookieJar. It can be extended as you wish. What I did is to implement a CookieJar and build the OkHttpClient using the OkHttpClient.Builder with this this CookieJar.
public class MyCookieJar implements CookieJar {
private List<Cookie> cookies;
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
this.cookies = cookies;
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
if (cookies != null)
return cookies;
return new ArrayList<Cookie>();
}
}
Here is how you can create the OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cookieJar(new MyCookieJar());
OkHttpClient client = builder.build();
right now I'm playing with it. try PersistentCookieStore, add gradle dependencies for JavaNetCookieJar:
compile "com.squareup.okhttp3:okhttp-urlconnection:3.0.0-RC1"
and init
// init cookie manager
CookieHandler cookieHandler = new CookieManager(
new PersistentCookieStore(ctx), CookiePolicy.ACCEPT_ALL);
// init okhttp 3 logger
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// init OkHttpClient
OkHttpClient httpClient = new OkHttpClient.Builder()
.cookieJar(new JavaNetCookieJar(cookieHandler))
.addInterceptor(logging)
.build();
`
Adding compile "com.squareup.okhttp3:okhttp-urlconnection:3.8.1"
to your build.gradle.
And then adding
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
.cookieJar(new JavaNetCookieJar(cookieManager))
.build()
helped me without adding any third-party dependency except the one from OkHttp.