我如何使用 JsonObjectRequest 发送正文数据? Android-凌空图书馆

How do i send body data with a JsonObjectRequest? Android-Volley library

我正在尝试发送数据到我的服务器。我创建了一个 JsonObject 并在创建 JsonObjectRequest 时将其作为 参数 传递。它不会给出任何 error,但不会返回任何内容。试过邮递员,它工作正常。

这是我的代码:

    JSONObject jsonBody = new JSONObject();

    try {
        jsonBody.put("firstname", "asd");
        jsonBody.put("lastname", "asd");
        jsonBody.put("id", "1");
    } catch (JSONException e) {
        e.printStackTrace();
    }



    //creating a JsonObjectRequest
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showPlayersUrl,
    jsonBody, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            JSONArray players;
            try{
                players = response.getJSONArray("Players");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    requestQueue.add(jsonObjectRequest);
}

试一试:

RequestQueue queue = Volley.newRequestQueue(this);

private void makeJsonObjReq() {
showProgressDialog();
        Map<String, String> postParam= new HashMap<String, String>();
        postParam.put("un", "xyz@gmail.com");
        postParam.put("p", "somepasswordhere");

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
        Const.URL_LOGIN, new JSONObject(postParam),
        new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
                msgResponse.setText(response.toString());
                hideProgressDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideProgressDialog();
            }
        }) {

    @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;
    }



};

jsonObjReq.setTag(TAG);
queue.add(jsonObjReq);



}

好的,找到问题了。服务器端我不接受 json 格式的数据。只需添加这个就可以了:

$_POST = json_decode(file_get_contents('php://input'), true);