-
-
Save tsuharesu/cbfd8f02d46498b01f1b to your computer and use it in GitHub Desktop.
/** | |
* 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()); |
Look elsewhere on how to use as a singleton. I use Dagger to inject my OkHttpClient, for example.
with lib 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0' it as simple as just add
JavaNetCookieJar jncj = new JavaNetCookieJar(CookieHandler.getDefault());
OkHttpClient.Builder()
.cookieJar(jncj)
.build();
I had some problems with this implementation, because you send back the cookies exactly as you get them, but it can append that there are more cookies with the same name, in my case the server sent me two phpsessid and it ended up with Unauthorized user. We need a cookie manager so marcinOz implementation is more accurate. And I would add that this is also for older version of okhttp-urlconnection.
This works create. Thanks buddy.
Thanks
https://gist.github.com/nikhiljha/52d45ca69a8415c6990d2a63f61184ff
I made a one size fits all, drag and drop approach based off of your gist.
This will "just work" and shouldn't require any work on your part (I hope).
Enjoy!
Thank you nikhiliha & tsuharesu
Your code saved my day
Thanks!
cool
is that means the app runs without worrying statefull web app sessions?
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 }
so a request has multi Cookie ?
cool thanks
Hey bro session id getting refreshed again and again what might be the reason. ?
Thank you so muuuuuch! For some reason, answer from SO https://stackoverflow.com/a/36865953/2098493 didn't work for me and also https://github.com/franmontiel/PersistentCookieJar.
Your solution persists server request cookie even if app is destroyed! :) I'm so happy. Finally found the right one.
Kotlin version with helper methods to create OkHttp client and Retrofit instance: https://gist.github.com/nikhiljha/52d45ca69a8415c6990d2a63f61184ff#gistcomment-2310417
Thank
@arvi can you please let me know how can you do that. persists server request cookie even if app is destroyed!. This one
Please the cookies are of which type e.g strings e.t.c cos i need that to create a custom response for retrofit
How to get url in AddCookiesInterceptor
Thanks
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.)
It really works. Thanks
Hey please can u provide an overall to how to implement this in singleton way.