如何使用 Java 构建与远程服务器交互的 HttpClient
我需要使用 java 编写一个 Http 客户端,它与有状态的 http 服务器交互。客户端需要
- 导航到登录页面并接受 cookie
- 提交登录页面,并填充 http 表单字段
- 选择商品并添加到购物车
- 提交购物车
我正在尝试使用 HttpClient 来实现此客户端。但是我发现即使我提交了登录表单,它仍然返回登录表单,就像我的提交无效一样。这是我的代码:
HttpClient agent = new DefaultHttpClient();
agent.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.RFC_2965);
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet(site);
HttpResponse response = agent.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
entity.getContent().close();
HttpPost post = new HttpPost(site + "/login.aspx");
post.getParams().setParameter("LoginControl1$ctlLoginName", "myusername");
post.getParams().setParameter("LoginControl1$ctlPassword", "mypassword");
response = agent.execute(post, localContext);
entity = response.getEntity();
String s = IO.readContentAsString(entity.getContent());
System.out.println(s);
知道我错在哪里吗?或者你有更好的方法来实现这个吗?
多谢 绿色的
I need to coding an Http Client using java which interact with a stateful http server. The client needs to
- navigate to login page and accept cookies
- submit login page with http form field filled
- select goods and add to shopping cart
- submit shopping cart
I am trying to use HttpClient to implement this client. However I found even I submitted the login form, it still return the login form just like my submit is invalid. Here is my code:
HttpClient agent = new DefaultHttpClient();
agent.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.RFC_2965);
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet(site);
HttpResponse response = agent.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
entity.getContent().close();
HttpPost post = new HttpPost(site + "/login.aspx");
post.getParams().setParameter("LoginControl1$ctlLoginName", "myusername");
post.getParams().setParameter("LoginControl1$ctlPassword", "mypassword");
response = agent.execute(post, localContext);
entity = response.getEntity();
String s = IO.readContentAsString(entity.getContent());
System.out.println(s);
Any idea where I am wrong? Or do you have better way to implement this?
Thanks a lot
Green
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不太确定可能出了什么问题,但是您是否考虑过使用 tcpdump/Wireshark 来获取与服务器的原始 HTTP 对话,并将您在 HTTPClient 中发送/接收的内容与提交时在 Web 浏览器中发送/接收的内容进行比较形式?
Not really sure what might be wrong, but have you considered using tcpdump/Wireshark to grab the raw HTTP conversation with the server and compare what you're sending/receiving in HTTPClient with what you send/receive in your web browser when you submit the form?