2016-10-27 438 views
0
 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", "[email protected]"); 
     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形式,可谷歌登錄頁面上編程中找到。在第一步中,我使用GET方法加載登錄頁面。在第二步中,我使用gaia_loginform表單中的加載數據創建連接,並通過POST提交表單。登錄谷歌帳戶使用Jsoup

因爲我期望看到一些錯誤消息,但只有登錄頁面返回沒有任何錯誤。我知道可能會有某種API用於Gmail操作,但現在我只是試圖登錄到目前爲止。

+0

你不能那樣做。您應該使用OAuth和Google的API。 – SLaks

+0

爲什麼?如果可以通過瀏覽器完成,我相信可以使用Jsoup或Selenium完成。其實我試圖下載谷歌錢包訂單報告,沒有那個API。 – user12384512

+0

Jsoup不是瀏覽器,它是非常有限的,硒可以做到這一點,我認爲這樣:) – quanlt

回答

1

我對硒的瞭解甚少,所以我不談論它。輸入電子郵件地址並按next後,Google帳戶將通過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(); 
+0

好吧,最後我設法使用Selenium登錄。不知道爲什麼上面的代碼不起作用,也許是因爲你提到的參數 – user12384512