背景:
使用httpClient请求某登录型网站,模拟一个操作,一般步骤一个httpclient模式登录-》httpClient模拟操作;
此时发现,每次操作都需要进行一次登录,极其浪费时间,是否可以通过某一方式进行一次登录多次操作,这里提供一种方式,带cookie登录。
登录获取cookie:
public String loginModel(String username, String password) {
String JSESSIONID = null;
HttpPost httppost = new HttpPost(url);//httppost
try {
List<NameValuePair> para = new ArrayList<NameValuePair>();
para.add(new BasicNameValuePair("password", password));
para.add(new BasicNameValuePair("username", username));//构造表单
httppost.setHeader(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
httppost.setEntity(new UrlEncodedFormEntity(para, "utf-8"));//设置请求体
BasicCookieStore cookieStore = new BasicCookieStore();//建立一个CookieStore
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();//建立带cookie的httpClient
int statuts_codes = httpClient.execute(httppost).getStatusLine().getStatusCode();//发送请求,发送成功后cookie将存在于cookieStore中
if (statuts_codes == HttpStatus.SC_OK) {//请求成功
List<Cookie> cookies = cookieStore.getCookies();//遍历获取需要的值
for (int i = ; i < cookies.size(); i++) {//获取JSESSIONID
if (cookies.get(i).getName().equals("id")) {
JSESSIONID = cookies.get(i).getValue();
}
}
cookieMap.put("JSESSIONID", JSESSIONID); } else {//请求失败 }
} catch (UnsupportedEncodingException ex) { } catch (IOException ex) { } finally {
httppost.releaseConnection();//释放资源
}
return cookieMap.get("JSESSIONID");
}
创建带有cookie的HttpClient
public CloseableHttpClient getHttpClients(String username, String password) {
BasicCookieStore cookieStore = new BasicCookieStore();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
String JSESSIONID = loginModel(username, password);
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", JSESSIONID);
cookie.setVersion(0);
String domain = Constant.HOOK_URL.substring(0, Constant.HOOK_URL.indexOf(":"));
if (Constant.HOOK_URL.startsWith("http://")) {
domain = Constant.HOOK_URL.substring(Constant.HOOK_URL.lastIndexOf("/") + 1, Constant.HOOK_URL.lastIndexOf(":"));
}
cookie.setDomain(domain);
cookie.setPath(Constant.HOOK_FW);
cookieStore.addCookie(cookie);
//带有cookie的httpclient
return httpClientBuilder.setDefaultCookieStore(cookieStore).build();
}
使用:
public void useCookieHttpClient() { CloseableHttpClient httpClient = getHttpClients(user, pass);
HttpPost httppost = new HttpPost(url2);
List<NameValuePair> para = new ArrayList<>();//表单
para.add("键", "值");
httppost.setEntity(new UrlEncodedFormEntity(para, "utf-8"));
httppost.setEntity(new UrlEncodedFormEntity(para, "utf-8"));
CloseableHttpResponse res = httpClient.execute(httppost);
int statuts_codes = res.getStatusLine().getStatusCode();
if (statuts_codes == HttpStatus.SC_OK) {//请求成功
String result = EntityUtils.toString(res.getEntity(), "utf-8");//返回值
} }