Add cookie to client request OkHttp

45,283

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>
Share:
45,283

Related videos on Youtube

Michael A
Author by

Michael A

Updated on July 09, 2022

Comments

  • Michael A
    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
    Michael A over 8 years
    thanks for the help, can you tell me how to construct a okhttp3.Cookie?
  • Michael A
    Michael A over 8 years
    Thanks! 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
    Michael A over 8 years
    Tried setting the header but it dont seem to work, on the server side no cookie is received
  • Tudor Luca
    Tudor Luca over 8 years
    @MichaelA the second solution, with the interceptor, will work regardless of your url.
  • Jesse Wilson
    Jesse Wilson over 8 years
    Try using addHeader("Cookie", "key=value") ?
  • Jesse Wilson
    Jesse Wilson over 8 years
    Double brace initialization is a bad idea for stack overflow code samples! No reason to show clever code when you can show simple code.
  • furiel
    furiel almost 8 years
    Just tested it and it doesn't work, the server doesn't receive the cookie
  • rciovati
    rciovati almost 8 years
    @furiel this is the correct method, your problem should be somewhere else. :)
  • Kaloglu
    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
    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
    TheLearner almost 7 years
    How can I log the cookie for testing purposes? @rciovati
  • TheLearner
    TheLearner almost 7 years
    How can I log the cookie for testing purposes @TudorLuca
  • sargas
    sargas over 5 years
    This answer seems to be for retrofit (which can use OkHttp), not for using OkHttp directly
  • ChaturaM
    ChaturaM about 5 years
    it works. try .addHeader("Cookie", "cookie-name=cookie-value")
  • Habil
    Habil over 3 years
    You save the day! Thanks.
  • JASIM CHOUHAN
    JASIM CHOUHAN about 3 years
    how to add this cookie to .addHeader()
  • ATutorMe
    ATutorMe over 2 years
    line 9: Arrays.asList(createNonPersistentCookie()); needs a return statement in method loadForRequest