理解 HttpClient 模擬登錄的關鍵,在於掌握瀏覽器與服務器的交互流程:
Set-Cookie: JSESSIONID=xxx → 瀏覽器自動保存 Cookiepackage com.artsoft.demo;
import java.io.FileOutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;
public class HttpClientDemo {
public static void main(String[] args) throws Exception {
getResoucesByLoginCookies();
}
private static void getResoucesByLoginCookies() throws Exception {
String username = "your_username";
String password = "your_password";
// 登錄接口(GET 方式攜帶參數,實際建議用 POST + 表單)
String urlLogin = "https://hx.buscoming.cn/Api/Security/Logon?UserCode=" + username + "&Password=" + password;
// 登錄後需訪問的受保護資源
String urlAfter = "https://hx.buscoming.cn/Api/Security/GetLoginAccount";
// 使用連接池管理器,提升高併發性能
DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());
// === 步驟 1:發起登錄請求,獲取 Cookie ===
HttpPost post = new HttpPost(urlLogin);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
// 關鍵:獲取並保存 CookieStore,後續請求將自動攜帶
CookieStore cookieStore = client.getCookieStore();
client.setCookieStore(cookieStore);
EntityUtils.consume(entity); // 釋放連接
// === 步驟 2:攜帶 Cookie 訪問受保護資源 ===
HttpGet get = new HttpGet(urlAfter);
response = client.execute(get);
entity = response.getEntity();
// 將響應寫入文件供驗證
String pathName = "d:/index.html";
writeHTMLtoFile(entity, pathName);
EntityUtils.consume(entity);
}
public static void writeHTMLtoFile(HttpEntity entity, String pathName) throws Exception {
byte[] bytes = EntityUtils.toByteArray(entity);
try (FileOutputStream fos = new FileOutputStream(pathName)) {
fos.write(bytes);
}
}
}
DefaultHttpClient 內部維護 CookieStore,執行登錄請求後,服務器返回的 Set-Cookie 標頭會被自動解析並存儲。後續使用同一 HttpClient 實例發起請求時,會自動在請求頭中添加 Cookie 標頭。
採用 PoolingClientConnectionManager 替代默認的單連接管理器,支持多線程環境下的連接復用,顯著提升高併發場景性能。
示例中為簡化將參數拼接在 URL 中,生產環境建議使用 UrlEncodedFormEntity 構建表單數據:
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("UserCode", username));
params.add(new BasicNameValuePair("Password", password));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
ClientProtocolException、IOException 等網絡異常EntityUtils.consume(entity) 確保連接釋放回連接池HttpClient 時調用 client.getConnectionManager().shutdown()HttpClient 通過 CookieStore 完美模擬瀏覽器的會話保持機制,核心在於「同一 HttpClient 實例執行登錄與後續請求」。掌握此模式,即可實現自動化測試、爬蟲采集、系統集成等多種登錄後操作場景。