问题描述
- HttpClient 模拟登录 Cookie问题
-
问题描述:向登录地址发起POST请求,提交登录验证信息,提示登录成功后发起另一个请求,返回提示“未登陆,请重新登陆”。
我这里用了同一个 HttpClient 实例,不知为何?DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPos("http://members.dota2.com.cn/dologin");
java.util.List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("username", "username"));
nvps.add(new BasicNameValuePair("passwd", "password"));
nvps.add(new BasicNameValuePair("rand", yzm));httpPost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
?????HttpEntity entity = response.getEntity();
?????String result = EntityUtils.toString(entity);
?????JSONObject json = JSONObject.fromObject(result);
?????System.out.println("登录系统返回信息:"+json.toString());
}
HttpPost httpPost = new HttpPost("http://event21.dota2.com.cn/dota2/activation/vipTester!contend.action");
java.util.List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("r", String.valueOf(Math.random())));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));HttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
?????HttpEntity entity = response.getEntity();
?????String result = EntityUtils.toString(entity);
?????JSONObject json = JSONObject.fromObject(result);
?????System.out.println("RETURN DATA : " + json.toString());
}
解决方案
你可以用fiddler监视一下请求,不行登陆之后把cookie取出来然后再发另一个请求之前把cookie再放进去。。。