java httpclient问题

用httpclient模拟登录一个网站,返回状态码(301或302等),我想不要处理返回状态码,直接用postMethod导向我要的页面,可以不考虑跳转吗?(不是说httpclient自动管理cookie,跳转应该可以忽略吧,哈哈,我的理解),求高手解释啊

4个回答

HttpClient支持自动转向处理,但是象POST和PUT方式这种要求接受后继服务的请求方式,暂时不支持自动转向,因此如果碰到POST方式提交后返回的是301或者302的话需要自己处理。

参考下例:
[code="java"]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();

// 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);[/code]

同时请参考一下下文,有些地方解释的非常详细。

http://yefeng.iteye.com/blog/112565

get方式可以自动处理跳转:)

你可以从postmethod里面取得responseHeader中的Set-Cookie字段,然后设置getmethod的requestHeader的Cookie字段。

楼主是想做删校内人气的工具么 :D

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问