模擬登錄學校 Struts2 系統(`.action` 後綴),登錄前後 URL 相同,無法靠頁面跳轉判斷。嘗試用 `JSESSIONID` Cookie 判斷,但發現請求與響應的 `JSESSIONID` 相同,無法區分。
CloseableHttpClient client = HttpClients.custom()
.setDefaultCookieStore(new BasicCookieStore())
.build();
// 1. 獲取初始 Cookie
HttpGet getLogin = new HttpGet(loginUrl);
client.execute(getLogin, response -> { /* 自動存 Cookie */ });
// 2. 提交登錄
HttpPost postLogin = new HttpPost(loginUrl);
postLogin.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
postLogin.setHeader("User-Agent", "Mozilla/5.0...");
postLogin.setHeader("Referer", loginUrl);
CloseableHttpResponse resp = client.execute(postLogin);
// 3. 判斷登錄成功
String html = EntityUtils.toString(resp.getEntity());
boolean success = html.contains("歡迎您") || html.contains("退出登錄");
// 或檢查重定向 Location Header
// 4. 後續使用同一 client(自動攜帶 Cookie)
HttpGet getInfo = new HttpGet(infoUrl);
client.execute(getInfo, ...);
Struts2 將用戶對象存入 `SessionMap`(`session.setAttribute("user", user)`)。攔截器檢查 Session 中是否有 `user` 對象決定是否放行。模擬登錄只需維持會話 Cookie,服務端自動關聯 Session。
不要盯著 `JSESSIONID` 變不變。登錄成功標誌是:服務端 Session 中寫入了用戶標識,客戶端憑 Cookie 訪問受保護資源返回授權內容。驗證方式:登錄後請求一個需要權限的接口/頁面,解析內容確認。