【问题标题】:Post JsonObject with Volley使用 Volley 发布 JsonObject
【发布时间】:2015-05-15 05:11:40
【问题描述】:

我正在尝试使用 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,只能接收。如果你想解决这个问题,你应该实现一个自定义类,但我真的不知道我是否只是在这里犯了一个愚蠢的错误(有可能)。

你们知道吗?

感谢您的宝贵时间。

【问题讨论】:

    标签: android json parse-platform android-volley


    【解决方案1】:

    您可以在不覆盖 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) {
    
            }
        });
    

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

    【讨论】:

    • 太棒了!很高兴我能帮忙:)
    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 2016-05-04
    相关资源
    最近更新 更多