Add cookie to client request OkHttp

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 23:33:54

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) {
                        final ArrayList<Cookie> oneCookie = new ArrayList<>(1);
                        oneCookie.add(createNonPersistentCookie());
                        return oneCookie;
                    }
                })
                .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(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                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.

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();

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>

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.

You should set headers in the interface declaration, like so: Call login(@Header("Cookie") String sessionId...)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!