HttpClient4.4 模仿登陸及維持同一session 請求
阿新 • • 發佈:2019-01-09
public class HttpClient { private static final Logger LOG = LogManager.getLogger(HttpClient.class); public static CloseableHttpClient httpClient = null; public static HttpClientContext context = null; public static CookieStore cookieStore = null; public static RequestConfig requestConfig = null; static { init(); } private static void init() { context = HttpClientContext.create(); cookieStore = new BasicCookieStore(); // 配置超時時間(連線服務端超時1秒,請求資料返回超時2秒) requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000) .setConnectionRequestTimeout(60000).build(); // 設定預設跳轉以及儲存cookie httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()) .setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig) .setDefaultCookieStore(cookieStore).build(); } /** * http get * * @param url * @return response * @throws ClientProtocolException * @throws IOException */ public static CloseableHttpResponse get(String url) throws ClientProtocolException, IOException { HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpget, context); try { cookieStore = context.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { LOG.debug("key:" + cookie.getName() + " value:" + cookie.getValue()); } } finally { response.close(); } return response; } /** * http post * * @param url * @param parameters * form表單 * @return response * @throws ClientProtocolException * @throws IOException */ public static CloseableHttpResponse post(String url, String parameters) throws ClientProtocolException, IOException { HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = toNameValuePairList(parameters); httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); CloseableHttpResponse response = httpClient.execute(httpPost, context); try { cookieStore = context.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { LOG.debug("key:" + cookie.getName() + " value:" + cookie.getValue()); } } finally { response.close(); } return response; } @SuppressWarnings("unused") private static List<NameValuePair> toNameValuePairList(String parameters) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); String[] paramList = parameters.split("&"); for (String parm : paramList) { int index = -1; for (int i = 0; i < parm.length(); i++) { index = parm.indexOf("="); break; } String key = parm.substring(0, index); String value = parm.substring(++index, parm.length()); nvps.add(new BasicNameValuePair(key, value)); } System.out.println(nvps.toString()); return nvps; } /** * 手動增加cookie * @param name * @param value * @param domain * @param path */ public void addCookie(String name, String value, String domain, String path) { BasicClientCookie cookie = new BasicClientCookie(name, value); cookie.setDomain(domain); cookie.setPath(path); cookieStore.addCookie(cookie); } /** * 把結果console出來 * * @param httpResponse * @throws ParseException * @throws IOException */ public static void printResponse(HttpResponse httpResponse) throws ParseException, IOException { // 獲取響應訊息實體 HttpEntity entity = httpResponse.getEntity(); // 響應狀態 System.out.println("status:" + httpResponse.getStatusLine()); System.out.println("headers:"); HeaderIterator iterator = httpResponse.headerIterator(); while (iterator.hasNext()) { System.out.println("\t" + iterator.next()); } // 判斷響應實體是否為空 if (entity != null) { // String responseString = EntityUtils.toString(entity); // System.out.println("response length:" + responseString.length()); // System.out.println("response content:" + responseString.replace("\r\n", "")); } System.out.println( "------------------------------------------------------------------------------------------\r\n"); } /** * 把當前cookie從控制檯輸出出來 * */ public static void printCookies() { System.out.println("headers:"); cookieStore = context.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { System.out.println("key:" + cookie.getName() + " value:" + cookie.getValue()); } } /** * 檢查cookie的鍵值是否包含傳參 * * @param key * @return */ public static boolean checkCookie(String key) { cookieStore = context.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); boolean res = false; for (Cookie cookie : cookies) { if (cookie.getName().equals(key)) { res = true; break; } } return res; } /** * 直接把Response內的Entity內容轉換成String * * @param httpResponse * @return * @throws ParseException * @throws IOException */ public static String toString(CloseableHttpResponse httpResponse) throws ParseException, IOException { // 獲取響應訊息實體 HttpEntity entity = httpResponse.getEntity(); if (entity != null) return EntityUtils.toString(entity); else return null; } }