使用Jsoup

时间:2016-10-27 16:41:36

标签: java jsoup

        Connection.Response loginPage = Jsoup.connect("https://accounts.google.com/ServiceLogin?elo=1")
                .method(Connection.Method.GET)
                .execute();

        Document loginDocument = loginPage.parse();
        Element form = loginDocument.getElementById("gaia_loginform");

        Connection connection1 = Jsoup.connect("https://accounts.google.com/signin/challenge/sl/password")
                .cookies(loginPage.cookies())
                .method(Method.POST);

        Elements inputElements = form.getElementsByTag("input");
        for (Element inputElement : inputElements) {
            String key = inputElement.attr("name");
            String value = inputElement.attr("value");
            if (value != null && key != null && !key.equals("")) {
                connection1.data(key, value);
            }

        }
        connection1.data("Email", "myemeailv@gmail.com");
        connection1.data("Passwd", "mypassword");

        // trying to load gmail
        Response response = connection1.execute();
        Connection.Response main = Jsoup.connect("https://mail.google.com/mail/u/0/?tab=wm#inbox")
            .method(Connection.Method.GET)
            .cookies(response.cookies())
            .execute();

        System.out.println(main.body());

在上面的代码中,我尝试提交 gaia_loginform 表单,该表单可以在Google登录页面上以编程方式找到。在第一步,我使用GET方法加载登录页面。在第二步,我使用来自 gaia_loginform 表单的加载数据创建连接,并通过POST提交表单。

结果我希望看到一些错误消息,但只返回登录页面而没有任何错误。我知道可能存在某种用于Gmail操作的API,但现在我只想尝试登录。

1 个答案:

答案 0 :(得分:1)

我对硒知之甚少,所以我不谈论它。输入电子邮件地址并按下一步后,谷歌帐户将通过ajax向浏览器发送一些额外的参数(例如:bgresponse),它们将被添加到邮件参数中,而不仅仅是之前的参数。

您收到登录页面的原因是因为您发送了不同的请求而没有正确的Cookie,并且Google会重定向到登录页面。

 Connection.Response main = Jsoup.connect("https://mail.google.com/mail/u/0/?tab=wm#inbox")
            .method(Connection.Method.GET)
            .cookies(response.cookies())
            .execute();