Sunday, 1 September 2013

Checking if authorized access on http get response

Checking if authorized access on http get response

I'm trying to check whether the user and password is correct. I'm
consuming an API and here's my code :
String username = user.getText().toString(), password =
pass.getText().toString();
String URL = "MyUrl";
String authData = "Basic " + Base64.encodeToString((username + ":" +
password).getBytes(), Base64.NO_WRAP);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Authorization", authData);
HttpResponse response = null;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
String s = EntityUtils.toString(entity);
Toast.makeText(getBaseContext(), s,
Toast.LENGTH_SHORT).show();
Intent i = new Intent(Login.this,DriverLogin.class);
startActivity(i);
finish();
}
else
Toast.makeText(getBaseContext(), "Fail",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// Auto-generated catch block
e.printStackTrace();
}
finally {
}
I've got no problem if the username and password is correct. My problem is
when the user inputted an incorrect login credentials. I have a line there
checking if entity is not null. As I observed, whether the login
credentials is right or wrong it goes in this condition. When correct, it
displays the details I need. When wrong, it displays a message that
details are not authorize. I want to catch that message in order to say
that login credentials is wrong. I thought that if the details is wrong,
entity will be null. Any ideas? Thanks!

No comments:

Post a Comment