Android登录网站 - 总是返回登录页面数据
我有一个登录表单,当前正在使用HTTP Post Request登录参数并登录到网站。我不确定服务器类型,因此可能是问题所在。一旦获得登录凭证,它就会将输入流转换为一个字符串(所有html)并将其设置为textview。这里的登录:Android登录网站 - 总是返回登录页面数据
private void postLoginData() throws ClientProtocolException, IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("loginurl"); // Changed for question.
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("sid", "username"));
nameValuePairs.add(new BasicNameValuePair("pin", "pass"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String finalres = inputStreamToString(response.getEntity().getContent()).toString();
tvStatus.setText(finalres);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
而这里的inputStreamToString()
private StringBuilder inputStreamToString(InputStream is) throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
的问题是,它永远只是返回登录页面的HTML。当用户在网站上登录失败时,它会有一条消息来表明这一点。即使我添加不正确的凭据,它也不会显示任何不同的内容。同样,如果我添加正确的登录名,它仍然显示我只是登录页面的HTML。
检查HTTP状态。做这样的事情
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//Do Something here.. I'm logged in.
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
// Do Something here. Access Denied.
} else {
// IF BOTH CASES not found e.g (unknown host and etc.)
}
这将完全符合你想要检查的状态。谢谢
它总是返回第一个结果。 – 2012-03-31 04:59:20
如果它出现在第一个条件中,那么这意味着您已成功登录。现在,它取决于您需要使用该身份验证所做的事情。 – 2012-03-31 05:00:27
问题是,即使我输入了不正确的登录名,也会发生相同的结果。 – 2012-03-31 05:05:45
登录后是否需要获取页面内容?如果它是200或401,请检查HTTP状态。如果只是想进行身份验证,则不需要获取数据。 – 2012-03-31 04:37:17
您能否指出我在检查HTTP状态方面的正确方向?我一直在使用Google,并且找不到它。 – 2012-03-31 04:40:56
写入response.getStatusLine()。getStatusCode();到Logcat。 – yorkw 2012-03-31 04:50:10