Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...