我正在尝试使用我的帐户凭据通过发布请求登录网站。当我使用 curl 来执行我的 post 请求时,一切正常,但是当我尝试在 java 中实现它时却HttpURLConnection没有。当我发送一个带有Content-Type: application/x-www-form-urlencoded作为标题的发布请求并且username=USERNAME&password=PASSWORD作为我https://******.de/login/index.php的响应的有效负载包含一个Set-Cookie: Session=sodfsgpc0uefhn4sdfucnau2; path=/.如果我现在获取此会话 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条经验 获得超8个赞
经过更多工作后,我发现 login.php 站点将请求重定向到另一个页面,如果您不使用 login.php 返回的会话 ID 请求它,该页面会使您的会话 ID 无效。
所以打电话connection.setFollowRedirects(false);给我修好了。
添加回答
举报
0/150
提交
取消
