For OkHttp3, a simple accept-all, non-persistent CookieJar
implementation can be as follows:
OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(new CookieJar() {
private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url, cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url);
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.build();
Or if you prefer to use java.net.CookieManager
, include okhttp-urlconnection
in your project, which contains JavaNetCookieJar
, a wrapper class that delegates to java.net.CookieHandler
:
dependencies {
compile "com.squareup.okhttp3:okhttp:3.0.0"
compile "com.squareup.okhttp3:okhttp-urlconnection:3.0.0"
}
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
OkHttpClient client = new OkHttpClient.Builder()
.cookieJar(new JavaNetCookieJar(cookieManager))
.build();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…