HttpClient post 提交数据问题

xiaolinshu 2010-03-21 07:09:52
我想用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());

}

这段代码打印的信息时登录界面,这是为什么?
...全文
2058 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
slzwx2004 2010-07-14
  • 打赏
  • 举报
回复
你确定你的rul是对的吗?
因为httpClient要求的URL是提交的URL噢(即form中的action),并不是登录页面的URL
xu452057005 2010-06-23
  • 打赏
  • 举报
回复
教妳个解决办法吧!
1.查看是否登录成功。的Header[] 请求,和Cookie 用工具在网站中登录查询下参数
如果是和登录成功的请求一样那就说明是跳转问题
登录后查询一个登录后的界面 get
//登录成功之后跳转
get.setFollowRedirects(true);
get.getParams().setParameter (HttpMethodParams.SINGLE_COOKIE_HEADER, true);
2.没有登录成功,可以设置下//设置流量器兼容 Cookie策略
client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
有几个版本 自己去看下API咯。!
jwmwdxxxx 2010-03-27
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 xiaolinshu 的回复:]

首先感谢楼上

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


Header locationHeader = postMethod.getResponseHeader("location");
System.out.println(locationHeader);
location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
} else {
System.err.println("Location field value is null.");
}


你要先判断下页面是否进行了跳转,如果跳转了,从header里把新url取取来,然后再链接到新的url才能读到跳转后的代码。
xiaolinshu 2010-03-26
  • 打赏
  • 举报
回复
首先感谢楼上

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

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());
  • 打赏
  • 举报
回复
我的博客有关于httpclient的例子,不妨去看下 http://hi.baidu.com/孤独的皮蛋
  • 打赏
  • 举报
回复
你登陆成功后跳转到了哪里。
岁月之梦 2010-03-24
  • 打赏
  • 举报
回复
你要吧用户名和密码封装到cookie里面去!带cookie过去!
susuifeng 2010-03-24
  • 打赏
  • 举报
回复
http://www.doaction.cn/blog/post/java-httpclient.html.......路过
Ark032425 2010-03-22
  • 打赏
  • 举报
回复
登陆验证没有通过吧。
看一下服务端是否登陆成功。根据场景推算,应该登陆失败的

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧