我正在嘗試使用我的帳戶憑據(jù)通過發(fā)布請求登錄網(wǎng)站。當我使用 curl 來執(zhí)行我的 post 請求時,一切正常,但是當我嘗試在 java 中實現(xiàn)它時卻HttpURLConnection沒有。當我發(fā)送一個帶有Content-Type: application/x-www-form-urlencoded作為標題的發(fā)布請求并且username=USERNAME&password=PASSWORD作為我https://******.de/login/index.php的響應的有效負載包含一個Set-Cookie: Session=sodfsgpc0uefhn4sdfucnau2; path=/.如果我現(xiàn)在獲取此會話 ID 并將其設置為 cookie 以對我進行身份驗證,則它適用于 curl 請求的會話 ID,但不適用于 java 請求。卷曲:curl -v -H "Content-Type: application/x-www-form-urlencoded" --data "username=USERNAME&password=PASSWORD" https://******.de/login/index.php爪哇String loginData = "username=USERNAME&password=PASSWORD";URL url = new URL(LOGIN_URL);HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();connection.setRequestMethod("POST");connection.addRequestProperty("Accept", "*/*");connection.addRequestProperty("Host", "******.de");connection.addRequestProperty("Content-Length", String.valueOf(loginData.length));connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");connection.setRequestProperty("User-Agent", "curl/7.55.1");connection.setDoOutput(true);OutputStream out = connection.getOutputStream();out.write(loginData);out.flush();out.close();connection.getInputStream().close();System.out.println(connection.getHeaderField("Set-Cookie").split(";")[0]);如您所見,我嘗試使用 curl 使用的相同標頭,但即便如此,它似乎也不起作用。
1 回答

慕田峪9158850
TA貢獻1794條經(jīng)驗 獲得超7個贊
經(jīng)過更多工作后,我發(fā)現(xiàn) login.php 站點將請求重定向到另一個頁面,如果您不使用 login.php 返回的會話 ID 請求它,該頁面會使您的會話 ID 無效。
所以打電話connection.setFollowRedirects(false);
給我修好了。
添加回答
舉報
0/150
提交
取消