【问题标题】:Login to website via Java?通过Java登录网站?
【发布时间】:2024-05-15 19:10:01
【问题描述】:

我正在尝试使用 java 制作一个程序,通过插入用户名和密码来访问这个website,然后在我登录时从帐户中获取一些数据。我通过谷歌搜索了很多并尝试了一些 @987654322 @但我没有太多运气来实现这一目标。有什么建议吗?

【问题讨论】:

  • 你得到什么错误信息?
  • 我没有收到任何错误,只是收到了这条消息Successfully made the HTPP POST,然后是Recevied response is:,然后是页面内容
  • 向我们展示您现在正在使用的代码。
  • 以编程方式登录大学网站可能违反了他们的政策。

标签: java javascript http


【解决方案1】:

您使用的代码是旧技术; Commons HttpClient 是一个更简单、更强大的选项,并且有大量的示例和在线文档。如果您不反对 Ruby,我会将Watir 加入其中;或者,如果您实际上不需要代码,而只想要一个简单的记录播放自动化,Selenium 是一个不错的选择。

【讨论】:

    【解决方案2】:

    缺乏对语言的理解,我无法给你具体的建议。

    但是要走的路是检查网页上的表格。然后您可以向此处定义的站点发送发布请求。

    作为帖子正文,您发送表单的参数,就像它们显示为 URL 参数一样。

    <!-- language: lang-js -->
        String payload = "password=test&user=test" // password and user must be replaced with the names of the form fields and test with password and username respectively
        HttpURLConnection configConnection = new URL(formTarget).openConnection();
        System.out.println("+------------------------------------------------------");
        System.out.println("| Request ");
        System.out.println("+------------------------------------------------------");
        System.out.println("| URL: " + configConnection.getURL());
        System.out.println("+------------------------------------------------------");
        System.out.println("| Payload ");
        System.out.println("+------------------------------------------------------");
        System.out.println(payload);
        configConnection.setDoOutput(true);
        configConnection.setRequestMethod("POST");
    
        configConnection.getOutputStream().write(payload.getBytes());
        InputStream xmlInputStream = configConnection.getInputStream();
    
        int _byte = -1;
        ByteArrayOutputStream bios = new ByteArrayOutputStream();
        while ((_byte = xmlInputStream.read()) > -1) {
            bios.write(_byte);
        }
        final byte[] responseBytes = bios.toByteArray();
        String responseString = new String(responseBytes);
        System.out.println("+------------------------------------------------------");
        System.out.println("| Response ");
        System.out.println("+------------------------------------------------------");
        System.out.println("| Code: " + configConnection.getResponseCode());
        System.out.println("+------------------------------------------------------");
        System.out.println(responseString);
        System.out.println("+------------------------------------------------------");
    

    为了更好地解析输出,您可以使用tagsoup 库将其转换为正确的 xhtml。

    【讨论】:

    • 没有这种方法:write(String)
    • configConnection.getOutputStream().write(payload.getBytes()); // 忘记在我的示例中更改此内容
    • isCompressed() 呢?
    • 更正了示例来自的更复杂客户端库的残余部分。
    最近更新 更多