Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic cookie handling with OkHttp 3

I am using okhttp 3.0.1.

Every where I am getting example for cookie handling that is with okhttp2

OkHttpClient client = new OkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); 

Can please some one guide me how to use in version 3. setCookieHandler method is not present in the version 3.

like image 949
user2672763 Avatar asked Jan 19 '16 16:01

user2672763


2 Answers

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(); 
like image 52
franmontiel Avatar answered Oct 13 '22 07:10

franmontiel


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

`

like image 20
1f7 Avatar answered Oct 13 '22 07:10

1f7