What is required to log into a website using Jsoup? I believe my code is correct, but I have never successfully logged into a website using Jsoup so I might be missing something. Here is my code:
try {
String url = ("http://quadrigacx.com/login");
Connection.Response loginForm = (Connection.Response)Jsoup.connect(url)
.method(Connection.Method.GET)
.execute();
Document loginDoc = loginForm.parse();
Elements loginElements = loginDoc.select("input:not([name=client_id]):not([name=password])");
int i = 0;
String v[] = new String[loginElements.size()];
for (Element element: loginElements){
v[i++] = element.attr("value");
}
int ii = 0;
String n[] = new String[loginElements.size()];
for (Element element: loginElements){
n[ii++] = element.attr("name");
}
Connection.Response loginFormLogin = (Connection.Response)Jsoup.connect(url)
.cookies(loginForm.cookies())
.data(n[0],v[0])
.data("client_id", "xxxxxxx")
.data("password", "xxxxxx")
.data(n[1],v[1])
.data(n[2],v[2])
.method(Connection.Method.POST)
.execute();
Document document2 = Jsoup.connect("http://quadrigacx.com/settings")
.cookies(loginFormLogin.cookies())
.get();
System.out.print(document2.toString());
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
document2
returns a login page which shows it didn't successfully log in. There is a input value named time
, and I think that it might be why it doesn't work. It is a value that goes up over time; I ran the code twice and the time variables returned 1511226860
and 1511226876
. My code takes about 10 seconds to print the doc, so maybe the time
variable has already changed by the time it sends the post request? I am not sure whether this is the problem. Maybe there is something else I'm not seeing? Thanks.
Edit: Here is the code, I post the authenticate after I have already logged in with the user Id and password. loginCookies
are the cookies from the first login. Connection.Response auth = Jsoup.connect("https://quadrigacx.com/authenticate")
.userAgent("Mozilla")
.method(Connection.Method.POST)
.cookies(loginCookies)
.data("google_code", googleCode.getText())
.data("email_code", emailCode.getText())
.data("authenticate", "Authenticate")
.followRedirects(true)
.execute();
I have also tried:
byte[] gcText = googleCode.getText().getBytes(ISO_8859_1);
String gcValue = new String(gcText, UTF_8);
byte[] ecText = emailCode.getText().getBytes(ISO_8859_1);
String ecValue = new String(ecText, UTF_8);
Connection.Response auth = Jsoup.connect("https://quadrigacx.com/authenticate")
.userAgent("Mozilla")
.method(Connection.Method.POST)
.cookies(loginCookies)
.data("google_code", gcValue)
.data("email_code", ecValue)
.data("authenticate", "Authenticate")
.followRedirects(true)
.execute();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…