如何将整数和字符串作为参数发送给JsonObjectRequest(Android)

时间:2017-11-04 09:30:04

标签: java php android sql-server json

我需要将5个字符串和3个整数作为参数发送到我的服务器。我一直收到这个错误:“缺少所需的参数(姓名,电子邮件,密码,性别或dob)!” [在我的PHP代码末尾找到] 。如何将多个基元类型作为参数发送到我的服务器?在搞乱这段代码之前,我使用了一个StringRequest和一个HashMap作为重写方法的返回类型:getParams()。我现在已经添加了整数... dob_day,dob_month和dob_year并且遇到了麻烦。这是一些代码...

private void registerUser(final String first_name,  final String last_name, final String email, final String password, final String gender, final int dob_day, final int dob_month, final int dob_year) {

        // Tag used to cancel the request
        String cancel_req_tag = "register";

        progressDialog.setMessage("Verifying Registration...");
        showDialog();

        JSONObject jObj = new JSONObject();
        try {
            jObj.put("first_name", first_name);
            jObj.put("last_name", last_name);
            jObj.put("email", email);
            jObj.put("password", password);
            jObj.put("gender", gender);
            jObj.put("dob_day", dob_day);
            jObj.put("dob_month", dob_month);
            jObj.put("dob_year", dob_year);
            Log.i("jsonString", jObj.toString());
        } catch(Exception e) {
            e.printStackTrace();
        }

        JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
                URL_FOR_REGISTRATION, jObj, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    boolean error = response.getBoolean("error");

                    if (!error) {
                        String user = response.getJSONObject("user").getString("first_name");
                        Toast.makeText(getApplicationContext(), "Registration Successful! \nWelcome, " + user +"!", Toast.LENGTH_LONG).show();

                        SharedPreferences preferences = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString(PREF_USERNAME, signupInputEmail.getText().toString());
                        editor.apply();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {

                        String errorMsg = response.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            /**
             * Passing some request headers
             */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }
        };
        // Adding request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonReq, cancel_req_tag);
    }
}

服务器端:

<?php

require_once 'update_user_info.php';
$db = new update_user_info();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['gender']) && isset($_POST['dob_day']) && isset($_POST['dob_month']) && isset($_POST['dob_year'])) {

    // receiving the post params
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $gender = $_POST['gender'];
    $dob_day = $_POST['dob_day'];
    $dob_month = $_POST['dob_month'];
    $dob_year = $_POST['dob_year'];

    // check if user is already existed with the same email
    if ($db->CheckExistingUser($email)) {
        // user already existed
        $response["error"] = TRUE;
        $response["error_msg"] = "User already exists with email:" . $email;
        echo json_encode($response);
    } else {
        // create a new user
        $user = $db->RegisterUser($first_name, $last_name, $email, $password, $gender, $dob_day, $dob_month, $dob_year);
        if ($user) {
            // user stored successfully
            $response["error"] = FALSE;
            $response["user"]["first_name"] = $user["first_name"];
            $response["user"]["last_name"] = $user["last_name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["gender"] = $user["gender"];
            $response["user"]["dob_day"] = $user["dob_day"];
            $response["user"]["dob_month"] = $user["dob_month"];
            $response["user"]["dob_year"] = $user["dob_year"];
            echo json_encode($response);
        } else {
            // user failed to store
            $response["error"] = TRUE;
            $response["error_msg"] = "Registration Error!";
            echo json_encode($response);
        }
}
} else {
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters (name, email, password, gender or dob) is missing!";
    echo json_encode($response);
}
?>

1 个答案:

答案 0 :(得分:1)

您正在向您的php脚本发送json文本。

但是你的php脚本需要POST参数。

不兼容的设置。

您有两种方法可以使它们兼容。

- 您可以更改您的PHP脚本以接收json文本。

- 您可以更改发送方以标准方式发送帖子参数。