Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...