使用REST API使用POST方法在Android中登录示例

时间:2015-02-16 19:54:31

标签: android json android-asynctask

我正在开发我的第一个Android应用程序,我们有自己的REST API,url就像。 “www.abc.com/abc/def/”。对于登录活动,我需要通过传递3个参数作为标识符,电子邮件和密码来进行httppost。然后在获得http响应后,我需要显示对话框是否无效凭据或切换到另一个活动。

有人可以告诉我如何执行此操作的示例代码吗?

2 个答案:

答案 0 :(得分:11)

完成此任务的一种简单方法是使用库,如果您熟悉库。我推荐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();
    }

为什么我们需要尝试&amp; catch,首先我们被迫,另一方面,如果JSON解析出现问题,它将阻止应用程序崩溃。

答案 1 :(得分:3)

这是你如何从头开始处理这个问题,在你的登录活动中使用这个代码块,如果你使用POST方法,你会稍微修改一下因为我使用GET方法来检查信用证, LoginHandler扩展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);


        }

    }