首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java HttpClient 登入路由器並重啟:表單登入 + Cookie 維持會話

     編輯:程式設計綜合問答

原始碼缺陷

直接將 Basic base64(user:pass) 加入 Header,大多數路由器採用**表單登入 + Session Cookie**,不支援 HTTP Basic Auth。

正確流程

  1. POST 登入表單:提交 username/password 到登入頁 (如 /login.cgi)。
  2. 獲取 Set-Cookie:從回應標頭提取 Session ID (如 sessionid=xxx)。
  3. 攜帶 Cookie 請求重啟 API:後續請求帶上 Cookie: sessionid=xxx。

完整範例

CloseableHttpClient client = HttpClients.custom()
    .setDefaultCookieStore(new BasicCookieStore()) // 自動管理 Cookie
    .build();

// 1. 登入
HttpPost login = new HttpPost("https://192.168.1.1/login.cgi");
login.setEntity(new UrlEncodedFormEntity(Arrays.asList(
    new BasicNameValuePair("username", "admin"),
    new BasicNameValuePair("password", "123456")
), Consts.UTF_8));
client.execute(login); // Cookie 自動存入 CookieStore

// 2. 重啟
HttpGet reboot = new HttpGet("https://192.168.1.1/userRpm/SysRebootRpm.htm?Reboot=%E9%87%8D%E5%90%AF%E8%B7%AF%E7%94%B1%E5%99%A8");
HttpResponse resp = client.execute(reboot);
System.out.println(EntityUtils.toString(resp.getEntity()));

關鍵點

  • 使用 BasicCookieStore 讓 HttpClient 自動處理 Cookie 存取。
  • 登入 URL、參數名需抓包確認 (F12 Network 或 Wireshark)。
  • 部分路由器需 Referer、User-Agent、CSRF Token,請完整模擬瀏覽器行為。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved