我是初学者,我只是找不到可行的解决方案。
我想要做什么:用户输入用户名和密码,应用程序登录到网站。如果登录不成功,则返回 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 的代码可以正常工作,所以我不会把整个HttpRequest类放在这里,只放最重要的方法:
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;
}
所以,我缺少的是来自 Authentication 类的部分代码,我需要在其中查看它是否成功登录。我不知道如何处理我得到的结果变量(或response或entity)。