httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); httpClient.getHostConfiguration().setHost("www.xiaonei.com", 80, "http"); String url = "http://login.xiaonei.com/Login.do"; PostMethod method = new PostMethod(url); NameValuePair email = new NameValuePair( "email" , "" );//邮箱 NameValuePair password = new NameValuePair( "password" , "" );//密码 method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gb2312"); NameValuePair[] data = { email,password}; method.setRequestBody(data); try {
httpClient.executeMethod(method); Cookie[] cookies=httpClient.getState().getCookies(); httpClient.getState().addCookies(cookies); method.releaseConnection(); int state = method.getStatusCode();
参考
http://www.cnblogs.com/yesun/archive/2008/03/18/903319.html
登陆成功后,肯定有一个Session ID返回,
一般保存在Cookie中比较多。
发送请求的时候,发送相应的cookie就可以了。
关键字 httpclient session
httpclient 会话
httpclient cookie
httpClient.getHostConfiguration().setHost("www.xiaonei.com", 80, "http");
String url = "http://login.xiaonei.com/Login.do";
PostMethod method = new PostMethod(url);
NameValuePair email = new NameValuePair( "email" , "" );//邮箱
NameValuePair password = new NameValuePair( "password" , "" );//密码
method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gb2312");
NameValuePair[] data = { email,password};
method.setRequestBody(data);
try {
httpClient.executeMethod(method);
Cookie[] cookies=httpClient.getState().getCookies();
httpClient.getState().addCookies(cookies);
method.releaseConnection();
int state = method.getStatusCode();
// System.out.print(state);
String newUrl = "";
if ((state == HttpStatus.SC_MOVED_TEMPORARILY) || (state == HttpStatus.SC_MOVED_PERMANENTLY) || (state == HttpStatus.SC_SEE_OTHER) || (state == HttpStatus.SC_TEMPORARY_REDIRECT)){
Header header = method2.getResponseHeader("location");
if(header != null){
newUrl = header.getValue(); //获得跳转页面地址
//System.out.println("newUrl: "+newUrl);
if(newUrl == null || newUrl.equals("")){
newUrl = "/";
}
String urlx=null;
//以get方式请求跳转页面
GetMethod getMethod = new GetMethod(newUrl);
getMethod.setRequestHeader("Cookie",cookies.toString());
httpClient.excuteMethod(getMethod);
getMethod.releaseConnection();
urlx="rundll32 url.dll,FileProtocolHandler "+newUrl;
Runtime.getRuntime().exec("cmd.exe /c start "+ urlx);
如果前后的SessionId不一致,尝试重写或改写Cookie。
一般HttpClient会自动完成的啊,
呵呵,以前遇到过这个问题,但是现在想不起来怎么解决的了。还有一种可能,是因为,楼主在登录和跳转两个操作的时候,创建了两个不同对象,
从而导致服务端产生了两个Session分配给客户端了。
楼主使用同一个对象试试,记得把TCP的监控器打开,这样可以抓到响应的包进行分析的。