volley用法之 以post方式发送 json 参数
需求是這樣
我們需要發(fā)送一個(gè)post請(qǐng)求向服務(wù)器要參數(shù)。要求是發(fā)送的post參數(shù)也要是json格式。
簡單一點(diǎn)的是這樣的:
如果要發(fā)送的是這樣簡單的json格式,我們可以簡單的使用map來實(shí)現(xiàn):
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>() {@Overridepublic void onResponse(JSONObject response) {Log.d(TAG, "response -> " + response.toString());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.e(TAG, error.getMessage(), error);}}) {@Overridepublic 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);這個(gè)方法,可以很方便的將map轉(zhuǎn)成json數(shù)據(jù)。
如果需要傳的是個(gè)有嵌套的json數(shù)據(jù)又該怎么辦呢?
例如:
相比之前的數(shù)據(jù),我們看到?merchant?也是一個(gè)json Object
這種嵌套的格式該怎么寫呢?也很簡單這里是嵌套,我們也寫一個(gè)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的參數(shù):
參數(shù)一:
請(qǐng)求方式 (這里是post)
參數(shù)二:
請(qǐng)求的URL
參數(shù)三:
請(qǐng)求的參數(shù)(如果是get請(qǐng)求方式則為空 null)
參數(shù)四:
服務(wù)器相應(yīng)的回調(diào)(可以根據(jù)服務(wù)器的相應(yīng)碼區(qū)分不同的情況)
參數(shù)五:
服務(wù)器未響應(yīng)的回調(diào)(可以做一些簡單的提示)
?
?
謝謝閱讀!
?
轉(zhuǎn)載于:https://www.cnblogs.com/wobeinianqing/p/5939928.html
總結(jié)
以上是生活随笔為你收集整理的volley用法之 以post方式发送 json 参数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Error和Exception的区别
- 下一篇: dns服务 很多问题,后续再研究