Post 带有 Volley 的 JsonObject

Post JsonObject with Volley

我正在尝试发送 Post 请求但没有成功。

库工作正常,我设法发送了一些字符串请求,但是带有 JsonObject 的 Post 不工作。

String urlJsonReq = "https://api.parse.com/1/classes/GameScore";
    String tag_json_obj = "tag_json";

    JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
            urlJsonReq,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("MyApp", response.toString());
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d("MyApp", "Error: " + error.getMessage());
                    // hide the progress dialog
                }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("value1", "testValue1");
            params.put("value2", "testValue2");
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("X-Parse-REST-API-Key", "xxxxxxxxxxxx");
            headers.put("X-Parse-Application-Id", "xxxxxxxxxxx");
            return headers;
        }

        @Override
        public String getBodyContentType() {
            return "application/json";
        }
    };

我一直收到错误消息。我在某处读到,但没有任何详细信息表明 volley 无法发送 JsonObjects,只能接收。如果你想解决这个问题,你应该实现一个自定义 class,但我真的不知道我是否只是犯了一个愚蠢的错误(这是可能的)。

你们知道吗?

感谢您的宝贵时间。

您可以在不覆盖 getParams 或 getBodyContentType 的情况下发送 JSONObject。例如这样的东西

JSONObject object = new JSONObject();
    JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

显然,如果需要,您可以覆盖 headers。