There are two ways to 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 sentence is what you need.
You can find a working example here .
source share