免責聲明
本文僅供技術研究與教學用途,展示 HTTP 協議模擬登入的通用流程。請勿用於爬蟲、暴力破解或任何違反目標網站服務條款的行為。實際京東登入涉及加密、驗證碼、風控、OAuth2 等複雜機制,此範例為簡化示範。
核心流程
- GET 登入頁,解析隱藏欄位(
uuid、動態 token 等)。
- POST 登入 API,攜帶帳號、密碼、隱藏欄位、Cookie。
- 處理 302 重導向,攜帶 Cookie 訪問導向目標。
- 驗證登入成功(檢查回應內容或 Cookie)。
關鍵程式碼片段 (HttpClient 4.5)
public class JdLoginSimulator {
private static final String LOGIN_PAGE = "https://passport.jd.com/new/login.aspx";
private static final String LOGIN_API = "https://passport.jd.com/uc/loginService";
private static final String REDIRECT_URL = "https://order.jd.com/center/list.action";
private final CloseableHttpClient client = HttpClients.custom()
.setDefaultCookieStore(new BasicCookieStore())
.build();
public boolean login(String username, String password) throws Exception {
// 1. 獲取登入頁,解析隱藏欄位
String loginPageHtml = executeGet(LOGIN_PAGE);
Map<String, String> hiddenFields = parseHiddenFields(loginPageHtml);
// 2. 準備 POST 參數
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("loginname", username));
params.add(new BasicNameValuePair("nloginpwd", password));
params.add(new BasicNameValuePair("loginpwd", password));
params.add(new BasicNameValuePair("ReturnUrl", REDIRECT_URL));
hiddenFields.forEach(params::add);
// 3. 執行登入 POST
HttpPost post = new HttpPost(LOGIN_API);
post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
post.setHeader("Referer", LOGIN_PAGE);
post.setHeader("User-Agent", "Mozilla/5.0...");
try (CloseableHttpResponse resp = client.execute(post)) {
int status = resp.getStatusLine().getStatusCode();
if (status == 302) {
Header loc = resp.getFirstHeader("Location");
if (loc != null) {
// 4. 跟隨重導向
return followRedirect(loc.getValue());
}
}
// 解析 JSON 回應判斷成功
String json = EntityUtils.toString(resp.getEntity());
return json.contains("\"success\":true");
}
}
private boolean followRedirect(String url) throws Exception {
HttpGet get = new HttpGet(url);
try (CloseableHttpResponse resp = client.execute(get)) {
return resp.getStatusLine().getStatusCode() == 200;
}
}
private String executeGet(String url) throws IOException {
HttpGet get = new HttpGet(url);
try (CloseableHttpResponse resp = client.execute(get)) {
return EntityUtils.toString(resp.getEntity());
}
}
private Map<String, String> parseHiddenFields(String html) {
Map<String, String> map = new HashMap<>();
// 使用 Jsoup 或正則解析
// 此處略過具體解析邏輯
return map;
}
public void close() throws IOException { client.close(); }
}
現代網站登入難點與對策
| 難點 | 說明 | 對策 |
| 密碼加密 | RSA/AES 前端加密,公鑰動態獲取 | 逆向 JS 加密邏輯,或使用 Selenium/Playwright 真實瀏覽器 |
| 驗證碼/滑塊 | 行為分析、圖形驗證碼 | 第三方打碼平台、模擬軌跡(高風險) |
| 風控/設備指紋 | Canvas、WebGL、電池、字體指紋 | 指紋瀏覽器、住宅代理 IP |
| OAuth2 / SSO | 跳轉至授權中心 | 模擬完整重導向鏈,保持 Cookie |
建議方案
- 官方 API:京東開放平台提供 OAuth2 授權,合規獲取訂單/商品資料。
- 瀏覽器自動化:Playwright / Selenium 真實渲染引擎,自動處理 JS/加密/驗證碼(較慢但穩健)。
- 合規爬蟲:遵守
robots.txt、限制頻率、標識 User-Agent、提供聯絡方式。