获取cookie
public static String HBLogin(String loginName,String loginPassword,String url) throws IllegalStateException, IOException{
HttpClient client = new DefaultHttpClient();
//设置登录参数
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("uname", loginName));
formparams.add(new BasicNameValuePair("upwd", loginPassword));
formparams.add(new BasicNameValuePair("Action", "Login"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
//新建Http post请求
HttpPost httppost = new HttpPost(url);
httppost.setEntity(entity);
//处理请求,得到响应
HttpResponse response = client.execute(httppost);
String set_cookie = response.getFirstHeader("Set-Cookie").getValue();
String cookie = set_cookie.substring(0,set_cookie.indexOf(";"));
return cookie;
}
登陆
public static String getCon(String cookie,String url){
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Cookie", cookie);
HttpResponse response = null;
try {
response = httpclient.execute(get);
return EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
测试登陆
String cookie = HttpClientUtils.HBLogin("账号", "密码", "url");
String domStr = HttpClientUtils.getCon(cookie, fetchingUrl);