Add cookie to client request OkHttp
Solution 1
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.
Solution 2
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();
Solution 3
I had the same needs, I made my own library. You can force set cookies like this with OkHttp3CookieHelper on https://github.com/riversun/okhttp3-cookie-helper .
String url = "https://example.com/webapi";
OkHttp3CookieHelper cookieHelper = new OkHttp3CookieHelper();
cookieHelper.setCookie(url, "cookie_name", "cookie_value");
OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(cookieHelper.cookieJar())
.build();
Request request = new Request.Builder()
.url(url)
.build();
Gradle
compile 'org.riversun:okhttp3-cookie-helper:1.0.0'
Maven
<dependency>
<groupId>org.riversun</groupId>
<artifactId>okhttp3-cookie-helper</artifactId>
<version>1.0.0</version>
</dependency>
Related videos on Youtube
Michael A
Updated on July 09, 2022Comments
-
Michael A almost 2 years
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
-
Michael A over 8 yearsthanks for the help, can you tell me how to construct a okhttp3.Cookie?
-
Michael A over 8 yearsThanks! do you have an example for using the Cookie builder? also, if i want to set cookie on the domain level and not a specific full url?
-
Michael A over 8 yearsTried setting the header but it dont seem to work, on the server side no cookie is received
-
Tudor Luca over 8 years@MichaelA the second solution, with the interceptor, will work regardless of your url.
-
Jesse Wilson over 8 yearsTry using addHeader("Cookie", "key=value") ?
-
Jesse Wilson over 8 yearsDouble brace initialization is a bad idea for stack overflow code samples! No reason to show clever code when you can show simple code.
-
furiel almost 8 yearsJust tested it and it doesn't work, the server doesn't receive the cookie
-
rciovati almost 8 years@furiel this is the correct method, your problem should be somewhere else. :)
-
Kaloglu over 7 years@RiccardoCiovati I use this block with PersistentCookieJar but I can not add to Header or different interceptor to. When I add just PCJ its ok but when added new interceptor for headers (Accept, Envoirement etc) CookieJar not working. do you have any suggestion?
-
rciovati over 7 years@Kaloglu I don't, sorry. Perhaps it'd be better to post your own question with a code example so that people could reproduce your problem.
-
TheLearner almost 7 yearsHow can I log the cookie for testing purposes? @rciovati
-
TheLearner almost 7 yearsHow can I log the cookie for testing purposes @TudorLuca
-
sargas over 5 yearsThis answer seems to be for retrofit (which can use OkHttp), not for using OkHttp directly
-
ChaturaM about 5 yearsit works. try .addHeader("Cookie", "cookie-name=cookie-value")
-
Habil over 3 yearsYou save the day! Thanks.
-
JASIM CHOUHAN about 3 yearshow to add this cookie to .addHeader()
-
ATutorMe over 2 yearsline 9:
Arrays.asList(createNonPersistentCookie());
needs a return statement in methodloadForRequest