Apache Commons HttpClient 3.1(舊版 API,穩定廣泛使用),依賴 commons-logging、commons-codec。核心優勢:自動維護 Cookie、支援 HTTPS/代理、完整 HTTP 方法封裝。
HttpClient、Cookie 陣列、代理 IP、登錄用戶,封裝 GET/POST/重定向處理、通用請求頭設置。public class BrowserContext {
private HttpClient client;
private Cookie[] cookies = new Cookie[0];
// ... proxy、user 管理
public String doGet(GetMethod get) throws IOException {
if (cookies != null) {
client.getState().addCookies(cookies);
get.addRequestHeader("Cookie", cookies.toString());
}
setCommonHeaders(get);
int status = client.executeMethod(get);
cookies = client.getState().getCookies(); // 更新 Cookie
if (status == 301 || status == 302) redirectToURL(get.getResponseHeader("Location").getValue());
return get.getResponseBodyAsString();
}
// doPost 同理,支援 ExpectContinueMethod
private void setCommonHeaders(HttpMethodBase m) {
m.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
m.setRequestHeader("Connection", "Keep-Alive"); // 關鍵:長連接
}
}
public class KaixinSitePost implements ISitePost {
private BrowserContext context;
public String login(Siteusers user, Proxyips ip) {
SiteLogin login = new SiteLogin(context, "https://login.kaixin.com/Login.do");
if (ip != null) login.getContext().setProxyip(ip);
Map params = new HashMap<>();
params.put("ss", "10106");
params.put("loginregFrom", "index");
params.put("origURL", "https://www.kaixin.com/SysHome.do");
params.put("email", user.getUsername());
params.put("password", user.getUserpwd());
login.addRequestParameters(params);
return login.login(user);
}
// post/reply 類似,構建參數調用 SitePost
}
client.getState().addCookies() + 手動添加 Cookie Header 雙重保險。HostConfiguration.setProxy(ip, port) + 認證憑證。HttpMethodParams.HTTP_CONTENT_CHARSET 解決中文亂碼。Connection: Keep-Alive 減少握手開銷。HttpClient 4.x/5.x API 變化巨大(CloseableHttpClient、HttpGet/HttpPost、RequestConfig 等),遷移時需重寫請求構建與響應處理邏輯,但核心設計模式(Context、SiteLogin、SitePost)可保留。