volley用法之 以post方式发送 json 参数

需求是这样

我们需要发送一个post请求向服务器要参数。要求是发送的post参数也要是json格式。

简单一点的是这样的:

如果要发送的是这样简单的json格式,我们可以简单的使用map来实现:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        Map<String, String> merchant = new HashMap<String, String>();
        merchant.put("id", "id");
        merchant.put("ncode", "ncode");
        merchant.put("tradingName", "tradingName");

        Log.d("map", map.toString());
        JSONObject jsonObject = new JSONObject(merchant);

        Log.e(TAG, "getdata: " + jsonObject.toString());

        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, "", jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, "response -> " + response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.getMessage(), error);
            }
        }) {

            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json; charset=UTF-8");

                return headers;
            }
        };
        requestQueue.add(jsonRequest);


    }
View Code

这里主要用到的就是

JSONObject jsonObject = new JSONObject(map);

这个方法,可以很方便的将map转成json数据。

如果需要传的是个有嵌套的json数据又该怎么办呢?

例如:

相比之前的数据,我们看到 merchant 也是一个json Object

这种嵌套的格式该怎么写呢?也很简单这里是嵌套,我们也写一个map的嵌套

就好啦!

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        Map<String, String> merchant = new HashMap<String, String>();
        merchant.put("id", "id");
        merchant.put("ncode", "ncode");
        merchant.put("tradingName", "tradingName");

        Map<String, Object> map = new HashMap<>();
        map.put("billType", "ADHOC");
        map.put("collectionCode", "string");
        map.put("otherRefNo", "string");
        map.put("contactMode", "SMS");
        map.put("merchant", merchant);
        map.put("currency", "SGD");
        map.put("amount", " 0.00");
        
        Log.d("map", map.toString());
        JSONObject jsonObject = new JSONObject(map);
//后面一样的,省略。
View Code

这样再使用 JSONObject 的方法就可以生成我们想要的json格式啦!很简单是吧。

下面来说下JsonRequest的参数:

参数一:

  请求方式 (这里是post)

参数二:

  请求的URL

参数三:

  请求的参数(如果是get请求方式则为空 null)

参数四:

  服务器相应的回调(可以根据服务器的相应码区分不同的情况)

参数五:

  服务器未响应的回调(可以做一些简单的提示)

谢谢阅读!

原文地址:https://www.cnblogs.com/wobeinianqing/p/5939928.html