如何使用 android 中的登录凭据向我的服务器进行身份验证?

How can I authenticate to my server with the Login credentials in android?

我是 Android 的新手,由于我是一名自学者,所以我一直遇到以下问题。 我在 MainActivity 中有一个简单的代码 as

   login.setOnClickListener(new View.OnClickListener() {

          @Override
           public void onClick(View view) {

            String sapCode = String.valueOf(sapcode.getText());
            String userName = String.valueOf(username.getText());
            String pwd = String.valueOf(password.getText());

            if (sapCode.equals("017343") && userName.equals("root") &&
                pwd.equals("root123")) {
                   message.setText("Login Successful!");
                   System.out.println("After successful and before Intent");
                   Intent intent = new Intent(context, HomeActivity.class);
                   startActivity(intent);
            } else {
                message.setText("Login Unsuccessful!");
            }
        }
    });

正如您在上面的代码中看到的那样,通过从视图中获取用户凭据,我通过提供硬编码值进行身份验证。

但实际上我应该通过在 post 方法中提供这些凭据来对我的 Web 应用程序进行休息调用以进行登录,而不是该代码。 URL 看起来像

http://myapp.co.in/login.do (or) http://myapp.co.in/rest/login

这样我的网络应用程序中的 java 代码就可以访问这些值并根据这些值进行身份验证。

现在我的问题是

1) 如何从我的 android 应用发出这样的请求?

2) 如果在我的 Web 应用程序中身份验证成功,那么我如何在我的 android 应用程序中管理会话?
我遇到过一些问题,并且一直坚持下去。任何帮助将不胜感激。谢谢你。

1. 要进行客户端 Web 服务调用,请使用 HttpURLConnection. The official tutorial is here;

2. 要在 Android 中保持会话,您可以使用 CookieStore or manually save, clear and retrieve the user_id or session_id in a SharedPreference.

给你。

编辑:

HttpClient should be used on Froyo & Eclair, while HttpURLConnection is preferred for Gingerbread and up. For the differences between the various connection approaches, see Android's HTTP Clients.