I am creating an app which needs to login to a website programmatically. I tried to use this code, but it doesn't log me in.
@Override
protected Boolean doInBackground(Void... arg0) {
try {
Connection.Response res = Jsoup.connect("http://omegastrike.co.uk/member.php?action=login")
.data("username", username, "password", password)
.followRedirects(true)
.method(Method.POST)
.execute();
Map<String, String> cookies = res.cookies();
Document doc2 = Jsoup.connect("http://omegastrike.co.uk/index.php")
.cookies(cookies)
.get();
System.out.println(doc2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Bonus question: How do I use this logged in connection for other functionalities in the app? Do I need to keep logging in?
So when you look at the login form for this page, the raw HTML looks like this:
<form method="post" action="member.php">
<table border="0" width="100%">
<tr>
<td>
<label for="login_username">Username:</label>
</td>
<td>
<input type="text" value="" style="width: 95%;" maxlength="30" size="25" name="username" class="textbox" id="login_username" />
</td>
</tr>
<tr>
<td>
<label for="login_password">Password:</label>
</td>
<td>
<input type="password" value="" style="width: 95%;" size="25" name="password" class="textbox" id="login_password" />
</td>
</tr>
<tr>
<td>
<label class="smalltext" title="If ticked, your login details will be remembered on this computer, otherwise, you will be logged out as soon as you close your browser."><input type="checkbox" value="yes" checked="checked" name="remember" class="checkbox"> Remember Me</label>
</td>
<td style="text-align: right;">
<input type="submit" value="Login" name="submit" id="button_postbit" />
</td>
</tr>
</table>
<input type="hidden" value="do_login" name="action" />
<input type="hidden" value="" name="url" />
</form>
As you can see, this is a POST
, to the URL http://omegastrike.co.uk/member.php
. There are several fields being submitted, not just username and password. The fields are:
[username] => namehere
[password] => passhere
[remember] => yes
[submit] => Login
[action] => do_login
So you need to include all of those in your POST request.
It would look something like this:
Connection.Response res = Jsoup.connect("http://omegastrike.co.uk/member.php")
.data("username", username, "password", password, "submit", "Login", "action", "do_login")
.followRedirects(true)
.method(Method.POST)
.execute();
As to staying logged in, I don't have an account with which to test, but generally there is a session id header or a cookie set upon login, that if included with subsequent requests, will keep you logged in.