【问题标题】:How to send both integers and strings as parameters for JsonObjectRequest (Android)如何将整数和字符串作为 JsonObjectRequest (Android) 的参数发送
【发布时间】:2017-11-04 09:30:04
【问题描述】:

我需要将 5 个字符串和 3 个整数作为参数发送到我的服务器。我不断收到此错误消息:“缺少必需的参数(姓名、电子邮件、密码、性别或出生日期)!” [在我的 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);
}
?>

【问题讨论】:

  • 参数类型没有问题,解决方法参考stackoverflow.com/a/31613565/2941375
  • "Required parameters (name, email, password, gender or dob) is missing!" 你没有发送'dob'。

标签: java php android sql-server json


【解决方案1】:

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

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

不兼容的设置。

您有两个选项可以使它们兼容。

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

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

【讨论】:

  • 如何更改我的 php 脚本以接收 json 文本?
  • 请不要问。你是需要这个的#12345。只是谷歌的例子。
猜你喜欢
  • 2018-11-16
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 2011-12-27
  • 2018-06-08
  • 1970-01-01
相关资源
最近更新 更多