新版本的HttpClient获取Cookies
使用CloseableHttpClient类实例化httpClient对象:
public static String doPost(Map<String, String> map, String charset) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
CookieStore cookieStore = new BasicCookieStore();
httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
httpPost = new HttpPost("http://localhost:8080/testtoolmanagement/LoginServlet");
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
httpClient.execute(httpPost);
String JSESSIONID = null;
String cookie_user = null;
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 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 (Exception ex) {
ex.printStackTrace();
}
return result;
}