模擬登錄後訪問需登錄頁面,核心是**獲取登錄響應的 Set-Cookie,後續請求帶上 Cookie**。
// 1. 登錄請求
URL loginUrl = new URL("https://localhost/ONCAPS/login.php");
HttpURLConnection conn = (HttpURLConnection) loginUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
String params = "user_id=test1&password=123456";
try (OutputStream os = conn.getOutputStream()) {
os.write(params.getBytes(StandardCharsets.UTF_8));
}
// 2. 獲取 Session Cookie
String sessionCookie = conn.getHeaderField("Set-Cookie"); // 如 JSESSIONID=abc123; Path=/
System.out.println("Cookie: " + sessionCookie);
// 3. 訪問受保護資源
URL infoUrl = new URL("https://localhost/ONCAPS/userInfo.php");
HttpURLConnection conn2 = (HttpURLConnection) infoUrl.openConnection();
conn2.setRequestProperty("Cookie", sessionCookie); // 關鍵:帶上 Cookie
conn2.setRequestProperty("User-Agent", "Mozilla/5.0");
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn2.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
setDoOutput(true) 必須在 getOutputStream() 前調用。Set-Cookie 可能包含多個 Cookie,需完整保存並原樣發回。