一、旧版本的 HttpClient 获取 Cookies
Ps:该方式官方已不推荐使用;使用 DefaultHttpClient 类实例化 HttpClient 对象。
publicstaticStringdooPost_deprecated(Stringurl, Map<String, String>map, Stringcharset) { DefaultHttpClienthttpClient=null; HttpPosthttpPost=null; Stringresult=null; try { httpClient=newDefaultHttpClient(); httpPost=newHttpPost(url); // 设置参数List<NameValuePair>list=newArrayList<NameValuePair>(); Iterator<Entry<String, String>>iterator=map.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String>elem= (Entry<String, String>) iterator.next(); list.add(newBasicNameValuePair(elem.getKey(), elem.getValue())); } if (list.size() >0) { UrlEncodedFormEntityentity=newUrlEncodedFormEntity(list, charset); httpPost.setEntity(entity); } HttpResponseresponse=httpClient.execute(httpPost); System.out.println(response.getStatusLine().getStatusCode()); StringJSESSIONID=null; Stringcookie_user=null; //获得CookiesCookieStorecookieStore=httpClient.getCookieStore(); List<Cookie>cookies=cookieStore.getCookies(); for (inti=0; i<cookies.size(); i++) { //遍历CookiesSystem.out.println(cookies.get(i)); System.out.println("cookiename=="+cookies.get(i).getName()); System.out.println("cookieValue=="+cookies.get(i).getValue()); System.out.println("Domain=="+cookies.get(i).getDomain()); System.out.println("Path=="+cookies.get(i).getPath()); System.out.println("Version=="+cookies.get(i).getVersion()); if (cookies.get(i).getName().equals("JSESSIONID")) { JSESSIONID=cookies.get(i).getValue(); } if (cookies.get(i).getName().equals("cookie_user")) { cookie_user=cookies.get(i).getValue(); } } if (cookie_user!=null) { result=JSESSIONID; } } catch (Exceptionex) { ex.printStackTrace(); } returnresult; }
二、新版本的 HttpClient 获取 Cookies
使用 CloseableHttpClient 类实例化 HttpClient 对象。
publicstaticStringdoPost(Map<String, String>map, Stringcharset) { CloseableHttpClienthttpClient=null; HttpPosthttpPost=null; Stringresult=null; try { CookieStorecookieStore=newBasicCookieStore(); httpClient=HttpClients.custom().setDefaultCookieStore(cookieStore).build(); httpPost=newHttpPost("http://localhost:8080/testtoolmanagement/LoginServlet"); List<NameValuePair>list=newArrayList<NameValuePair>(); Iterator<Map.Entry<String, String>>iterator=map.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String>elem= (Entry<String, String>) iterator.next(); list.add(newBasicNameValuePair(elem.getKey(), elem.getValue())); } if (list.size() >0) { UrlEncodedFormEntityentity=newUrlEncodedFormEntity(list, charset); httpPost.setEntity(entity); } httpClient.execute(httpPost); StringJSESSIONID=null; Stringcookie_user=null; List<Cookie>cookies=cookieStore.getCookies(); for (inti=0; i<cookies.size(); i++) { if (cookies.get(i).getName().equals("JSESSIONID")) { JSESSIONID=cookies.get(i).getValue(); } if (cookies.get(i).getName().equals("cookie_user")) { cookie_user=cookies.get(i).getValue(); } } if (cookie_user!=null) { result=JSESSIONID; } } catch (Exceptionex) { ex.printStackTrace(); } returnresult; }