本文展示如何使用 Java 原生 HttpURLConnection 模擬瀏覽器進行 GET/POST 請求,實現對特定論壇(示例為 t.vhao.net)的自動回帖。重點涵蓋 Cookie 處理、頁面存在性檢測、表單參數構造與反爬蟲應對。
⚠️ 法律與道德提醒:自動發帖/回帖可能違反網站服務條款,造成資源濫用。本文僅供技術學習參考,請勿用於生產環境或惡意灌水。
private static final String BASE_URL = "https://bbs.example.com/forum.php?mod=viewthread&tid=";
private static final String COOKIE = "your_cookie_here"; // 從瀏覽器複製
public static boolean isExist(int tid) {
try {
URL url = new URL(BASE_URL + tid);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Cookie", COOKIE);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 ...");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200) {
String html = IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8);
// 根據實際頁面特徵判斷
return !html.contains("指定的主題不存在或已被刪除");
}
} catch (IOException e) { log.error("檢測失敗 tid={}", tid, e); }
return false;
}
public static void reply(int tid, String content) {
if (!isExist(tid)) return;
try {
StringBuilder form = new StringBuilder(BASE_URL + tid);
Map params = new LinkedHashMap<>();
params.put("mod", "post");
params.put("action", "reply");
params.put("replysubmit", "yes");
params.put("infloat", "yes");
params.put("handlekey", "fastpost");
params.put("inajax", "1");
params.put("message", content);
params.put("formhash", "86ec5d81"); // 需從頁面提取或固定值
params.forEach((k, v) -> form.append("&").append(k).append("=").append(URLEncoder.encode(v, "UTF-8")));
URL url = new URL(form.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Cookie", COOKIE);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 ...");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(form.toString().getBytes(StandardCharsets.UTF_8));
}
if (conn.getResponseCode() == 200) {
String resp = IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8);
if (resp.contains("succeed")) log.info("回覆成功 tid={}", tid);
else log.warn("回覆失敗 tid={} resp={}", tid, resp);
}
} catch (IOException e) { log.error("回覆異常 tid={}", tid, e); }
}
public static void main(String[] args) {
int startTid = 774210;
for (int i = 0; i < 100; i++) {
reply(startTid + i, "友誼幫頂了");
// 隨機延時 15-30 秒,模擬人類行為
Thread.sleep(ThreadLocalRandom.current().nextLong(15000, 30000));
}
}
| 點 | 說明 |
|---|---|
| Cookie 獲取 | 瀏覽器 F12 Network → Request Headers → Cookie,複製完整字串。 |
| formhash | 防 CSRF 令牌,通常隱藏在表單中,需先 GET 頁面解析提取,或嘗試固定值。 |
| User-Agent | 必須模擬真實瀏覽器,否則易被 WAF 攔截。 |
| 編碼 | 統一 UTF-8,URLEncoder.encode 處理特殊字元。 |
| 連線池 | 生產建議用 Apache HttpClient / OkHttp 替換原生連線,支援連線復用、重試、攔截器。 |
原生 HttpURLConnection 雖繁瑣但無依賴,適合輕量級任務。實務中強烈建議使用 OkHttp 或 Apache HttpClient 5,配合 Jsoup 解析 HTML、Gson/Jackson 處理 JSON,構建健壯的爬蟲/自動化工具。切記遵守 robots.txt 與服務條款,技術服務於合規場景。