0

我正在尝试检查用户和密码是否正确。我正在使用 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 {
        }

如果用户名和密码正确,我没有问题。我的问题是当用户输入了不正确的登录凭据时。我在那里有一行检查实体是否不为空。正如我所观察到的,无论登录凭据是对还是错,它都会在这种情况下发生。正确时,它会显示我需要的详细信息。错误时,会显示信息未授权详细信息。我想捕获该消息以说明登录凭据错误。我认为如果细节错误,实体将为空。有任何想法吗?谢谢!

4

1 回答 1

2

您可以针对错误 401检查HttpResponse状态代码

if(response.getStatusLine() != null &&
   response.getStatusLine().getStatusCode() == 401) {
    // authentication is required and has failed or has not yet been provided
}
于 2013-09-02T05:59:11.650 回答