在阅读了几个资源以使HttpClient构造通过网站上可用的表单执行登录(POST方法)之后,我写了这个方法:
public void connect(View v) {
final String TAG = ">>>>>>>>>>>> Activity Log: ";
request = new HttpGet("http://www.mysite.com/login");
try {
response = client.execute(request);
} catch (ClientProtocolException e3) {
e3.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
entity = response.getEntity();
Log.d(TAG, "Login form get: " + response.getStatusLine());
if(entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Initial set of cookies:");
cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty())
{
Log.d(TAG, "None");
}
else
{
for(int i = 0; i<cookies.size(); i++)
{
Log.d(TAG, "- " + cookies.get(i));
}
}
String action = "/login.php";
String yourServer = "http://www.mysite.com";
post = new HttpPost(yourServer + action);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "myuser"));
params.add(new BasicNameValuePair("password", "mypass"));
try {
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
try {
response = client.execute(post);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
entity = response.getEntity();
Log.d(TAG, "Login form get: " + response.getStatusLine());
if(entity != null){
try {
entity.consumeContent();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Post logon cookies:");
cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty())
{
Log.d(TAG, "None");
}
else
{
for (int i = 0; i < cookies.size(); i++) {
Log.d(TAG, "- " + cookies.get(i));
}
}
}
但是无论我输入的用户名/密码我得到状态:“OK 200”。作为cookie我得到这样的东西:
[version:0] [name:PHPSESSID] [value: 9ismhf3p5c282p1east0drme02] [域: .mysite.com] [路径:/] [到期日: 空]
当我尝试访问某些无法登录用户的URL时,我会看到登录表单页面。我怎么知道我已成功登录并访问不可用的URL?
答案 0 :(得分:2)
嘿 我有同样的问题。您正在获取状态:“OK 200”,因为无论登录结果如何,该帖子都被视为成功。我的解决方案是检查响应实体。从本质上讲,这是一个字符串,其中包含您的帖子在浏览器中发送给用户的页面源。其中将是页面标题。例如:登录失败。虽然并不总是如此恰当地命名,但您只需手动登录然后使用view - &gt;即可轻松找到成功登录页面和不成功登录页面的标题。页面来源。
因此,解决方案将包含以下内容:
final String responseText = EntityUtils.toString(response.getEntity());
if (responseText.contains("<title>Login Failed<title>")
{
You failed
}
希望有所帮助。