21

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
  • 5,770
  • 16
  • 75
  • 127
  • You need to be more precise on what you're trying to do. Maybe some code? – Tudor Luca Mar 02 '16 at 09:41
  • @TudorLuca I need to send http (get post put) while attaching cookie to the request. in Java for example its done like this: URL url = new URL("http://www.google.com:80"); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", "name1=value1; name2=value2"); conn.connect(); – Michael A Mar 02 '16 at 09:45

4 Answers4

39

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.

blacktide
  • 10,654
  • 8
  • 33
  • 53
Tudor Luca
  • 6,259
  • 2
  • 29
  • 44
16

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();
rciovati
  • 27,603
  • 6
  • 82
  • 101
7

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>
riversun
  • 758
  • 8
  • 12
0

I think a better way to do this is by adding the cookie to the cookieJar. OkHttp will then automatically add the cookies to the request with an interceptor: https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/internal/http/BridgeInterceptor.java

cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
// add cookies to cookiejar
cookieJar.saveFromResponse("Cookie", listOfCookiesToAdd);

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cookieJar(cookieJar)

I didn't actually try this code, but it should work.

Wirling
  • 4,810
  • 3
  • 48
  • 78