背景:
使用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 = 0; 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");//返回值 } }