0
我是初學者,找不到可行的解決方案。如何在Android應用程序中實現登錄
我想要做什麼: 用戶輸入用戶名和密碼,然後應用程序登錄到網站。如果登錄失敗,它將返回false和正確的消息,否則返回true並繼續下一個活動(獲取另一個站點,解析html並顯示內容)。
我卡在哪裏:如何檢測登錄成功?
這裏是我的代碼
相關代碼LoginActivity:
Authentication auth = new Authentication();
boolean loginSuccess = auth.authenticateUser(username, pass);
if (!loginSuccess) {
Toast.makeText(getBaseContext(),
"Invalid username or password.",
Toast.LENGTH_SHORT).show();
}
else {
Intent intent = new Intent(LoginActivity.this, MenuActivity.class);
LoginActivity.this.startActivity(intent);
}
方法從認證類:
public boolean authenticateUser(String username, String pass) {
boolean loginSuccess = false;
HttpRequest httpRequest = new HttpRequest();
String result = "";
try {
result = httpRequest.getResult(username, pass);
Log.d("RESULT", result);
// Checking if it was a successful login
if (**SOMETHING**) loginSuccess = true;
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return loginSuccess;
}
因爲我得到的200(OK)狀態,我想POST的代碼工作正常,所以我不會把整個Ht tpRequest類在這裏,只有最重要的方法:
public String getResult(String username, String pass) throws ParseException, IOException {
String result = "";
response = postData(username, pass);
entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(response.getEntity());
}
return result;
}
public HttpResponse postData(String username, String password) throws ClientProtocolException, IOException {
HttpPost httpPost = getHttpPost(username, password);
HttpClient httpClient = getHttpClient();
return httpClient.execute(httpPost);
}
private HttpPost getHttpPost(String username, String password) throws UnsupportedEncodingException {
String url = "https://www.sitename.com/login.aspx";
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> parameters = new ArrayList<NameValuePair>(2);
parameters.add(new BasicNameValuePair("txtUsername", username));
parameters.add(new BasicNameValuePair("txtPassword", password));
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
return httpPost;
}
那麼,是什麼,我缺少的是從認證類,在這裏我要看看它是否是一個成功登錄的代碼的一部分。我不知道該怎麼辦結果變量,我得到(或迴應,或實體)。
事情是我檢查了無效和有效的登錄數據的狀態,它返回了相同的200代碼(我會重新檢查,但我敢肯定,我沒有犯一些錯誤)。此外,我嘗試輸入正確的用戶名和通行證,然後獲取下一個網站,但我得到的是相同的登錄頁面(雖然這可能與cookie有關?) – dronevil
是的我檢查,200狀態是不夠的,因爲我得到它用於無效的用戶名和密碼。還有其他建議嗎?我不知道。我嘗試閱讀響應內容,但我得到的只是一些html和css,沒有任何內容會指示登錄狀態。 – dronevil