Created
March 11, 2020 18:28
-
-
Save Odilio/c9b55aa6d5db7e90a621f05e8d3ba44c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package controllers; | |
import java.io.IOException; | |
import java.util.HashMap; | |
import org.jsoup.Connection; | |
import org.jsoup.Jsoup; | |
import org.jsoup.nodes.Document; | |
import org.jsoup.nodes.Element; | |
import org.jsoup.select.Elements; | |
public class JsoupLoginExample { | |
public static void main(String[] args) { | |
try { | |
// # Constants used in this example | |
final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"; | |
final String LOGIN_FORM_URL = "https://github.com/login"; | |
final String LOGIN_ACTION_URL = "https://github.com/session"; | |
final String USERNAME = "yourUsername"; | |
final String PASSWORD = "yourPassword"; | |
// # Go to login page and grab cookies sent by server | |
Connection.Response loginForm = Jsoup.connect(LOGIN_FORM_URL) | |
.method(Connection.Method.GET) | |
.userAgent(USER_AGENT) | |
.execute(); | |
Document loginDoc = loginForm.parse(); // this is the document containing response html | |
HashMap<String, String> cookies = new HashMap<>(loginForm.cookies()); // save the cookies to be passed on to next request | |
// # Prepare login credentials | |
String authToken = loginDoc.select("#login > form > div:nth-child(1) > input[type=\"hidden\"]:nth-child(2)") | |
.first() | |
.attr("value"); | |
HashMap<String, String> formData = new HashMap<>(); | |
formData.put("commit", "Sign in"); | |
formData.put("utf8", "e2 9c 93"); | |
formData.put("login", USERNAME); | |
formData.put("password", PASSWORD); | |
formData.put("authenticity_token", authToken); | |
// # Now send the form for login | |
Connection.Response homePage = Jsoup.connect(LOGIN_ACTION_URL) | |
.cookies(cookies) | |
.data(formData) | |
.method(Connection.Method.POST) | |
.userAgent(USER_AGENT) | |
.execute(); | |
System.out.println(homePage.parse().html()); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment