當 Java 程序需要訪問需要身份驗證的 URL 時,直接請求會因未登錄而失敗。解決思路:模擬登錄 → 獲取 Cookie → 後續請求攜帶 Cookie 證明身份。
// 登錄表單提交地址(從頁面 HTML 表單 action 獲取)
String loginUrl = "https://login.example.com/action/UserLogin";
URL url = new URL(loginUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 關鍵設置:允許輸出(發送 POST 數據)
conn.setDoOutput(true);
// 構造 POST 參數(參數名從 HTML 表單 input name 獲取)
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "GBK");
out.write("memberName=myUser&password=myPass");
out.flush();
out.close();
// 從響應頭獲取 Set-Cookie
String cookieVal = conn.getHeaderField("Set-Cookie");
System.out.println("登錄成功,Cookie: " + cookieVal);
String targetUrl = "https://user.example.com/dispatcher.php/module/Profile";
URL url2 = new URL(targetUrl);
HttpURLConnection resConn = (HttpURLConnection) url2.openConnection();
// 關鍵:設置 Cookie 請求頭
if (cookieVal != null) {
resConn.setRequestProperty("Cookie", cookieVal);
}
resConn.connect();
// 讀取響應內容
BufferedReader reader = new BufferedReader(
new InputStreamReader(resConn.getInputStream())
);
String line, content = "";
while ((line = reader.readLine()) != null) {
content += line;
}
reader.close();
System.out.println("受保護頁面內容: " + content);
// 可選:保存到本地文件
// Files.write(Paths.get("d:/profile.html"), content.getBytes());
setDoOutput(true) 開啟輸出流發送 POST 數據;getInputStream() 讀取響應。Set-Cookie 下發 Cookie;客戶端後續請求在請求頭 Cookie 攜帶。GBK(或目標站點編碼),讀取時用 InputStreamReader 指定對應編碼。Location 頭並持續攜帶 Cookie,或使用 CookieManager 自動管理。HttpURLConnection 預設不跟隨重定向,可用 setInstanceFollowRedirects(true) 開啟。