简体   繁体   中英

Login to Google account using 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());

In code above I'm trying to submit gaia_loginform form which can be found on Google login page programatically. On first step I load login page using GET method. On the second step I'm creation connection using loaded data from gaia_loginform form and submit form via POST.

As result I expect to see some error messages but only login page is returned without any errors. I know there could be some kind of API for Gmail manipulation, but now I'm just trying to login so far.

i know very little about selenium, so i dont talk about it. After enter email address and press next, google account will send some extra params to browser via ajax (for example:bgresponse), and they will be added to post params,not just previous params.

The reason you receive login page is because you send different request without proper cookies, and google redirect to login page.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM