如何使用JsonObjectRequest发送正文数据? Android-Volley库

时间:2018-12-22 10:03:16

标签: android android-volley

我正在尝试发送数据到我的服务器。我创建了JsonObject,并在创建JsonObjectRequest时将其作为 parameter 传递。它不会给出任何 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);
}

2 个答案:

答案 0 :(得分:0)

尝试一下:

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



}

答案 1 :(得分:0)

好,找到问题了。服务器端我不接受json格式的数据。只需添加它即可使用:

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