我正在尝试检查用户和密码是否正确。我正在使用API,这是我的代码:
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 {
}
如果用户名和密码正确,我没有问题。我的问题是用户输入了错误的登录凭据。我有一行检查实体是否为空。正如我所观察到的,无论登录凭据是对还是错,它都处于这种状态。如果正确,它会显示我需要的详细信息。如果错误,则会显示一条消息,指出详细信息未经授权。我想抓住该消息,以便说登录凭据是错误的。我认为如果细节错误,实体将为空。有任何想法吗?谢谢!
答案 0 :(得分:2)
您可以针对status code查看HttpResponse的error 401:
if(response.getStatusLine() != null &&
response.getStatusLine().getStatusCode() == 401) {
// authentication is required and has failed or has not yet been provided
}