Using HttpClient to Retrieve Cookies and Inject Them into Selenium for Login Automation
This article explains how to use Java HttpClient to call a login API, retrieve authentication cookies, and programmatically inject them into a Selenium WebDriver session, enabling automated tests to run in a logged‑in state without manual UI login.
During Selenium testing, many cases require a logged‑in state; instead of repeatedly performing UI login, the author demonstrates how to use HttpClient to call the login API, retrieve cookie values, and programmatically insert them into the browser.
The provided
public void loginByApi() throws InterruptedException, NoSuchAlgorithmException, JSONException, IOException {
ApiLibrary apiLibrary = new ApiLibrary(getUserName(), getUserPassWord()); //实例化接口类
Map<String, String> cookies = apiLibrary.getCookiesArguments(); //获取cookies信息
addCookie(cookies); //向浏览器插入cookies
sleep(1); //休眠等待
refresh(); //刷新
}method creates an ApiLibrary instance, obtains a Map<String, String> of cookies, adds them via addCookie, pauses briefly, and refreshes the page.
The
//获取cookies,map集合
public Map<String, String> getCookiesArguments() throws JSONException, IOException {
Map<String, String> cookiesArgs = new HashMap<String, String>(); //创建存放cookies的map集合
CloseableHttpClient httpClient = HttpClients.createDefault(); //创建并实例化连接对象
JSONObject jsonObject = new JSONObject(); //创建并实例化json对象
jsonObject.put("did", "web"); //设置登录类型
jsonObject.put("telnum", userMobile); //设置帐号
jsonObject.put("password", passWord); //设置密码
output(userMobile);
output(passWord);
String arguments = changeJsonToArguments(jsonObject); //将json对象转化为接口参数
String url = "http://beta-web.gaotu100.com/user/web/login"; //接口地址
HttpPost httpPost = new HttpPost(url + arguments); //创建并实例化post请求连接
CloseableHttpResponse response = httpClient.execute(httpPost); //执行请求获取响应
output(response.getStatusLine().getStatusCode()); //输出状态码
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
output("返回状态错误!");
}
HttpEntity entity = response.getEntity(); //获取响应实体
JSONObject ssString = new JSONObject(EntityUtils.toString(entity)); //获取响应实体的json数据
output(ssString.toString());
//获取相应数据
String chat_app_id = ssString.getString("chat_app_id");
String chat_name = ssString.getString("chat_name");
String chat_user_sig = ssString.getString("chat_user_sig");
String name = urlEncoderText(ssString.getString("name")); //对昵称进行转码
String sid = ssString.getString("session_id");
String role = "0"; //默认为0
//将数据存入map集合中
cookiesArgs.put("chat_app_id", chat_app_id);
cookiesArgs.put("chat_name", chat_name);
cookiesArgs.put("chat_user_sig", chat_user_sig);
cookiesArgs.put("name", name);
cookiesArgs.put("sid", sid);
cookiesArgs.put("role", role);
httpClient.close(); //关闭链接
return cookiesArgs; //返回map集合
}method builds and sends an HTTP POST request with JSON payload, parses the JSON response, extracts authentication fields, and stores them in a map.
The
public void addCookie(Map<String, String> args) {
Set<String> keys = args.keySet();
for(String key : keys){
driver.manage().addCookie(new Cookie(key, args.get(key)));
}
}helper iterates over the map and adds each cookie to the Selenium driver.
Finally, the article provides a curated list of technical and non‑technical resources for further reading.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
