Search code examples
javaandroidsharedpreferenceshttpurlconnectionandroidhttpclient

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


I'm very new to Android and since I'm a self learner I've been stuck with the following problem. I have a simple code in 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!");
            }
        }
    });

As you can see in the above code by taking user credentials from view, I'm authenticating by giving hard coded values.

But Instead to that code, Indeed I should make rest call to my webapplication for login by providing these credentials in a post method. The URL looks like

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

So that my java code inside my webapplication can access these values and authenticate based on those values.

Now My Questions are

1) How to make such request from my android app?

2) If authentication succeeded in my Web Application then how can I manage the session in my android app?
There are the problems I've been come across and I've been stuck with it. Any help will be appreciated. Thank you.


Solution

  • 1. To make a client web-service call, use HttpURLConnection. The official tutorial is here;

    2. To persist a session in Android, you can either make use of CookieStore or manually save, clear and retrieve the user_id or session_id in a SharedPreference.

    There you go.

    EDIT:

    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.