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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…