Example of logging into Android using the POST method using the REST API

I am working on my first Android application where we have our own REST API and the URL will be similar. "www.abc.com/abc/def/". For login activity, I need to do httppost, passing 3 parameters as an identifier, email and password. Then, having received the http response, I need to show a dialog box whether the Invalid Credentials are or are switched to another activity.

Can someone please show me a code example how to do this?

+4
source share
2 answers

, . Ion, . .

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

! , AndroidManifest.xml <application>, .

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

, onComplete ( // Result).:

    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();
    }

, , , , - JSON- .

+9

, , POST, , GET , LoginHandler extends AsyncTask, ...

private class  LoginHandler extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub

            String URL = "url to get from ";

            JSONObject jsonReader=null;


            try {

                // TODO Auto-generated method stub
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response;
                String responseString = null;
                try {
                    response = httpclient.execute(new HttpGet(URL));
                    StatusLine statusLine = response.getStatusLine();
                    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        response.getEntity().writeTo(out);
                        out.close();
                        responseString = out.toString();
                        jsonReader=new JSONObject(responseString);
                    } else {
                        // Closes the connection.
                        response.getEntity().getContent().close();
                        throw new IOException(statusLine.getReasonPhrase());
                    }
                } catch (ClientProtocolException e) {
                    // TODO Handle problems..
                    String er=e.getMessage();
                } catch (IOException e) {
                    // TODO Handle problems..
                    String er=e.getMessage();
                }

                // Show response on activity

                if (!jsonReader.get("UserName").toString().equals("")) {
                    SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
                    Editor editor = sp.edit();

                    editor.putString("email", jsonReader.getString("EmailAddress"));
                    editor.putString("username", jsonReader.getString("UserName"));
                    editor.putString("userid", jsonReader.getString("UserId"));
                    editor.putString("realname", jsonReader.getString("RealName"));
                    editor.putString("realsurname", jsonReader.getString("RealSurname"));
                    editor.putString("userprofileimage", jsonReader.getString("UserProfileImage"));




                    DateFormat dateFormat = new SimpleDateFormat(
                            "yyyy.MM.dd HH:mm:ss");
                    // get current date time with Date()
                    Date date = new Date();

                    editor.putString("LastLogin",
                            dateFormat.format(date.getTime()));
                    editor.commit();
                    return true;
                }
                return false;

            } catch (Exception ex) {

            }

            return false;
        }

        // TODO Auto-generated method stub

        @Override
        protected void onPostExecute(Boolean result) {
            // TODO Auto-generated method stub


            if (result) {
                pdialog.dismiss();
                Intent userMainActivityIntent = new Intent(
                         getApplicationContext(), MainUserActivity.class);
                startActivity(userMainActivityIntent);
            }
            else
            {
                pdialog.dismiss();
                new AlertDialog.Builder(MainActivity.this).setTitle("Login Error")
                .setMessage("Email or password is wrong.").setCancelable(false)
            .setPositiveButton("OK",new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.cancel();
                }
            } ).show();

            }




            super.onPostExecute(result);


        }

    }
+3

All Articles