Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add cookie to client request OkHttp

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

like image 630
Michael A Avatar asked Mar 02 '16 09:03

Michael A


2 Answers

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.

like image 192
Tudor Luca Avatar answered Oct 11 '22 06:10

Tudor Luca


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();
like image 22
rciovati Avatar answered Oct 11 '22 06:10

rciovati