I'm a beginner and I just can't find a solution that would work.
What I want to do: User types in username and password, and the application logs in to a website. If the login is unsuccessful it returns false and a proper message, otherwise it returns true and proceeds to the next activity (gets another site, parses html, and displays content).
Where I'm stuck at: How to detect a successful login?
Here's my code
Relevant code from 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);
}
Method from Authentication class:
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;
}
Since I get 200 (OK) status, I think the code for POST works ok, so I won't put the whole HttpRequest class here, just the most important methods:
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;
}
So, what I'm missing is part of the code from Authentication class, where I need to see if it was a successful login. I don't know what to do with result variable that I got (or response, or entity).