How to build an HttpClient interactive with remote server using Java
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 HttpG开发者_运维知识库et(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
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?
精彩评论