日期:2014-05-20  浏览次数:20588 次

HttpClient post 提交数据问题
我想用HttpClient 模拟用户登录,但是总是不能返回登录以后的界面(我有该网站的账号,因此用户名和密码都是正确的)
代码:
public static void main(String[] args) throws Exception {
HttpClient httpClient = new HttpClient();

PostMethod getMethod = new PostMethod(
"http://localhost:8080/login.jsp");

getMethod.setParameter("name", URLEncoder.encode("姓名 ", "gb2312"));
getMethod.setParameter("password", "2222");

httpClient.executeMethod(getMethod);

System.out.println(getMethod.getResponseBodyAsString());

}
 
这段代码打印的信息时登录界面,这是为什么?

------解决方案--------------------
Java code

PostMethod p = new PostMethod("http://xxxx.com");
// 参数       
NameValuePair email = new NameValuePair("email",
"xxxxxxxxxxx@126.com");
NameValuePair password = new NameValuePair("password", "xxxxxx");
NameValuePair[] params = new NameValuePair[] { email, password };
p.setRequestBody(params);
int status = c.executeMethod(p);
System.out.println(p.getResponseBodyAsString());

------解决方案--------------------
探讨

首先感谢楼上

我用你的方法试了结果一样
得到的status= c.executeMethod(p); 的值为200
但是 System.out.println(p.getResponseBodyAsString());打印的仍然是登录界面源代码

------解决方案--------------------
教妳个解决办法吧!
1.查看是否登录成功。的Header[] 请求,和Cookie 用工具在网站中登录查询下参数
如果是和登录成功的请求一样那就说明是跳转问题
登录后查询一个登录后的界面 get
//登录成功之后跳转
get.setFollowRedirects(true);
get.getParams().setParameter (HttpMethodParams.SINGLE_COOKIE_HEADER, true);
2.没有登录成功,可以设置下//设置流量器兼容 Cookie策略
client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
有几个版本 自己去看下API咯。!
------解决方案--------------------
你确定你的rul是对的吗?
因为httpClient要求的URL是提交的URL噢(即form中的action),并不是登录页面的URL