我正在创建一个需要以编程方式登录网站的应用。我试图使用此代码,但它并没有登录我。
@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;
}
奖金问题:如何将此登录连接用于应用中的其他功能?我需要继续登录吗?
答案 0 :(得分:1)
因此,当您查看此页面的登录表单时,原始HTML如下所示:
<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>
如您所见,这是POST
到网址http://omegastrike.co.uk/member.php
。提交了几个字段,而不仅仅是用户名和密码。字段是:
[username] => namehere
[password] => passhere
[remember] => yes
[submit] => Login
[action] => do_login
因此,您需要在POST请求中包含所有这些内容。
它看起来像这样:
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();
至于保持登录状态,我没有可以测试的帐户,但通常会在登录时设置会话ID标头或cookie,如果包含在后续请求中,则会让您保持登录状态。< / p>
答案 1 :(得分:1)
使用
...
Jsoup.connect("http://omegastrike.co.uk/member.php")
.data("username", username, "password", password, "submit", "Login", "action", "do_login")
...
答案 2 :(得分:0)
您可以使用Apache HTTP Components
。 HttpPost将为您完成这项工作。确保欺骗User-Agent
,因为某些服务器设置为仅接受某些浏览器。强烈建议使用Wireshark作为嗅探器。