【发布时间】:2021-09-19 10:29:21
【问题描述】:
我正在使用 OkHttp 登录网站。通过浏览器检查,我知道初始响应是 302 重定向,我最终应该得到 4 个 cookie:
但是,到目前为止,我尝试显示收到的 cookie 时显示响应为 200,并且只打印了 JSESSION ID cookie。
// COOKIE HANDLER
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
// INTERCEPTOR
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
// PROXY
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
// NEW CLIENT
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy)
.proxyAuthenticator(proxyAuthenticator)
.cookieJar(new JavaNetCookieJar(cookieHandler))
.addInterceptor(logging)
.build();
RequestBody formBody = new FormBody.Builder()
.add("user", "pass")
.build();
Request request = new Request.Builder()
.url("https://www.contoso.com")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.code());
CookieStore cookieStore = cookieManager.getCookieStore();
for (HttpCookie cookie : cookieStore.getCookies()) {
System.out.println("\n Cookie:" + cookie.getName());
System.out.println("\t Domain:" + cookie.getDomain());
System.out.println("\t Value:" + cookie.getValue());
}
重定向是导致我看不到所有 cookie 的原因吗?有没有办法捕获所有 cookie?我认为这与 302 有关。
如何查看cookieHandler中的内容?
【问题讨论】: