Java为什么不读取“Set-Cookie”标题?

时间:2016-04-01 05:44:24

标签: java httpurlconnection setcookie

我正在为客户申请。该网站是https // www.seekingarrangement.com / login

当我使用Chrome或Firefox时,我看到“Set-Cookie”的响应标头,其值为"laravel_session=eyJpdiI6InlXNkxTRzUxODRtR3BkT0xIR3ZDd0E9PSIsInZhbHVlIjoiMzlRaDdTSk1IRnNINjAyaWVvaGUrN25DYlJaRDVTNDVoMXBLWkdjaWNCN25Ldzg1UkVZazJ0c1JIVFhxODlMSytaRlk5Skd6Z0EyRG9XK29SUWhtOXc9PSIsIm1hYyI6ImFiNjdiYTczNDE4ZGMyOWViOTcxYTljZmUyNjhjY2ViM2E3N2ViMTBiMzBlYjA4MzgwZjhjOTVhNmVmMGM0OTMifQ%3D%3D; expires=Sat, 02-Apr-2016 04:19:15 GMT; Max-Age=82800; path=/; httponly

但是,当我运行以下代码时,“Set-Cookie”值为空。

private void onLoad() {
    CookieHandler.setDefault(new CookieManager());
    login();
}

private void login() {
    try {
       System.out.println("Logging in...");
       this.email = emailField.getText();
       this.password = passField.getText();

       /* 1.  connect to login url */  
       URL URL = new URL("https://www.seekingarrangement.com/login");
       HttpURLConnection conn = (HttpURLConnection) URL.openConnection();

       /* 2. GET response string */
       conn.setRequestMethod("GET");

       /* 3. Get Response cookies */
       Map cookiesTest = conn.getHeaderFields();
       String headerKeys[] = new String[cookiesTest.size()];
       String headerValues[] = new String[cookiesTest.size()];
       for(int i = 0;i<cookiesTest.size(); i++) {
           headerKeys[i] = conn.getHeaderFieldKey(i);
           headerValues[i] = conn.getHeaderField(i);
           System.out.println(i + ". " + headerKeys[i] + " : " + headerValues[i]);
       }

        // more code no relevant to my question
}

这使我在控制台中输出以下内容:

Logging in...
0. null : HTTP/1.1 200 OK
1. Server : cloudflare-nginx
2. Date : Fri, 01 Apr 2016 05:37:35 GMT
3. Content-Type : text/html; charset=UTF-8
4. Transfer-Encoding : chunked
5. Connection : keep-alive
6. Set-Cookie : 
7. X-Powered-By : PHP/5.6.14
8. Cache-Control : no-cache
9. Set-Cookie : 

如您所见,“Set-Cookie”响应标头都是空白的。但如果我查看任何浏览器的开发人员工具,它会显示“Set-Cookie”的实际值

1 个答案:

答案 0 :(得分:3)

如果删除以下行

CookieHandler.setDefault(new CookieManager());

它应该在您的sysout中显示Set-Cookie标题。

或者,如果您使用CookieManager,您应该能够看到存储在CookieStore中的Cookie,如下所示:

CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);

您可以在Cookie商店中查看Cookie:

if(manager.getCookieStore().getCookies().size() > 0)
{
    System.out.println("From cookieManager : " + manager.getCookieStore().getCookies());    
}