Search code examples
androidjsonandroid-asynctask

Login Example in Android using POST method using REST API


I am working on my First Android application where we have our own REST API, url will be like. "www.abc.com/abc/def/" . For login activity i need to do httppost by passing 3 parameters as identifier, email and password. Then after getting the http response, i need to show the dialogbox whether Invalid Credentials or Switch to another activity.

Can someone please show me sample code for how to do this?


Solution

  • An easy way to complete this task is to using a library, if your familiar with libraries. I recommend Ion because it's small and easy to work with. Add the library and add the following snippet to the method of your choice.

    Ion.with(getApplicationContext())
    .load("http://www.example.com/abc/def/")
    .setBodyParameter("identifier", "foo")
    .setBodyParameter("email", "[email protected]")
    .setBodyParameter("password", "p@ssw0rd")
    .asString()
    .setCallback(new FutureCallback<String>() {
       @Override
        public void onCompleted(Exception e, String result) {
            // Result
        }
    });
    

    Notice! If you want to make network calls you must add the following permission to your AndroidManifest.xml outside the <application> tag if you're not aware of that.

    <uses-permission android:name="android.permission.INTERNET" />
    

    To check the response for successful login, or failure you can add the following snippet inside the onComplete-method (where the // Result is).:

        try {
            JSONObject json = new JSONObject(result);    // Converts the string "result" to a JSONObject
            String json_result = json.getString("result"); // Get the string "result" inside the Json-object
            if (json_result.equalsIgnoreCase("ok")){ // Checks if the "result"-string is equals to "ok"
                // Result is "OK"
                int customer_id = json.getInt("customer_id"); // Get the int customer_id
                String customer_email = json.getString("customer_email"); // I don't need to explain this one, right?
            } else {
                // Result is NOT "OK"
                String error = json.getString("error");
                Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show(); // This will show the user what went wrong with a toast
                Intent to_main = new Intent(getApplicationContext(), MainActivity.class); // New intent to MainActivity
                startActivity(to_main); // Starts MainActivity
                finish(); // Add this to prevent the user to go back to this activity when pressing the back button after we've opened MainActivity
            }
        } catch (JSONException e){
            // This method will run if something goes wrong with the json, like a typo to the json-key or a broken JSON.
            Log.e(TAG, e.getMessage());
            Toast.makeText(getApplicationContext(), "Please check your internet connection.", Toast.LENGTH_LONG).show();
        }
    

    Why do we need a try & catch, well first of all we are forced to and on the other hand, it will prevent the application to crash if something goes wrong with the JSON-parsing.