So i started using Okhttp 3 and most of the examples on the web talk about older versions
I need to add a cookie to the OkHttp client requests, how is it done with OkHttp 3?
In my case i simply want to statically add it to client calls without receiving it from the server
There are 2 ways you can do this:
OkHttpClient client = new OkHttpClient().newBuilder()
.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
Arrays.asList(createNonPersistentCookie());
}
})
.build();
// ...
public static Cookie createNonPersistentCookie() {
return new Cookie.Builder()
.domain("publicobject.com")
.path("/")
.name("cookie-name")
.value("cookie-value")
.httpOnly()
.secure()
.build();
}
or simply
OkHttpClient client = new OkHttpClient().newBuilder()
.addInterceptor(chain -> {
final Request original = chain.request();
final Request authorized = original.newBuilder()
.addHeader("Cookie", "cookie-name=cookie-value")
.build();
return chain.proceed(authorized);
})
.build();
I have a feeling that the second suggestion is what you need.
You can find here a working example.
If you need to set a cookie for a single request you can just add the header:
Request request = new Request.Builder()
.addHeader("Cookie", "yourcookie")
.url("http://yoursite.com")
.build();
Otherwise, if you want to read cookies returned by the server and attach them to other requests you will need a CookieJar
. For Android you can use the PersistentCookieJar library which handles cookies properly and also saves them in the shared preferences:
ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(cookieJar)
.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With