用java登录网站

我想用java登录一个网站。 我使用的是org.apache.http,我已经写好了

HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("https://accounts.google.com/ServiceLogin? service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F%3Fhl%3Dsl%26tab%3Dwm%26ui%3Dhtml%26zy%3Dl&bsv=llya694le36z&scc=1&ltmpl=default&"); try { List nameValuePairs = new ArrayList(1); nameValuePairs.add(new BasicNameValuePair("vb_login_username", "XXX")); nameValuePairs.add(new BasicNameValuePair("vb_login_password", "XXX")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } 

它正确地发送了我已经测试过的post表格,但我仍然无法登录。 我想登录的网站是http://www.xtratime.org/forum/对此的任何想法还是有不同的方式?

 
  • 在提交页面之前编码密码( onsubmit )。 你应该在代码中做同样的事情。

  • action属性的值与您的代码( https://accounts.google.com... )不匹配。 您应该将post请求发送到login.php?do=login

并且有很多隐藏的领域:

      

您也应该发送这些参数。

通常,安装HttpFox Firefox Add-on更容易检查post参数的请求,而不是解码javascript。

我的浏览器发送这些post参数(用HttpFox捕获,密码是pass1 ):

 vb_login_username: user1 vb_login_password: s: 5d8bd41a83318e683de9c55a38534407 securitytoken: 0dcd78b4c1a376232b62126e7ad568e0d1213f95 do: login vb_login_md5password: a722c63db8ec8625af6cf71cb8c2d939 vb_login_md5password_utf: a722c63db8ec8625af6cf71cb8c2d939 

编辑

以下对我有用,我可以在打印的html代码中获得“感谢您登录”消息:

 final HttpClient client = new DefaultHttpClient(); final HttpPost post = new HttpPost( "http://www.xtratime.org/forum/login.php?do=login"); try { final List nameValuePairs = new ArrayList(1); nameValuePairs.add(new BasicNameValuePair("vb_login_username", "my user")); nameValuePairs.add(new BasicNameValuePair("vb_login_password", "")); nameValuePairs.add(new BasicNameValuePair("s", "")); nameValuePairs.add(new BasicNameValuePair("securitytoken", "inspected with httpfox, like f48d01...")); nameValuePairs.add(new BasicNameValuePair("do", "login")); nameValuePairs.add(new BasicNameValuePair("vb_login_md5password", "inspected with httpfox, like 8e6ae1...")); nameValuePairs.add(new BasicNameValuePair( "vb_login_md5password_utf", "inspected with httpfox, like 8e6ae1...")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); final HttpResponse response = client.execute(post); final BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (final IOException e) { e.printStackTrace(); } 

我建议你使用htmlunit :

HtmlUnit是一个“用于Java程序的GUI-Less浏览器”。 它模拟HTML文档,并提供一个API,允许您调用页面,填写表单,单击链接等…就像在“普通”浏览器中一样。

它具有相当好的JavaScript支持(不断改进),甚至可以使用相当复杂的AJAX库,根据您要使用的配置模拟Firefox或Internet Explorer。

它通常用于测试目的或从网站检索信息。