日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2023/12/13 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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>() {@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);

這個方法,可以很方便的將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

總結

以上是生活随笔為你收集整理的volley用法之 以post方式发送 json 参数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。