我在java web开发时候 尝试使用HttpClient post模拟登陆,可是无法获取到登陆的cookie
,之前在安卓开发时候Xutil可以直接获取,那么在WEB开发时候如何解决获取cookie的问题
CookieStore cookieStore = new BasicCookieStore();
HttpClientContext localContext = new HttpClientContext();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://xxx.net/loign.jsp");
localContext.setCookieStore(cookieStore);
httppost.setHeader("Content-Type", "text/html; charset=utf-8");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "username"));
formParams.add(new BasicNameValuePair("password", "password"));
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
httppost.setEntity(entity);
// 提交登录数据
HttpResponse re = httpclient.execute(httppost, localContext);
// 获取cookie
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {
System.out.println("Local Cookie:" + cookie);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://stackoverflow.com/questions/13847102/android-httpclient-and-cookies#
感谢。了解通过模拟表单提交来实现