如何发布参数作为JSON android系统中同时呼吁任何API(how to post param

2019-09-28 06:35发布

我是新来的Android开发,我需要张贴参数为JSON,同时调用任何API方法。

我传递一个数组列表:

List<NameValuePair> params = new ArrayList<NameValuePair>();

请给任何建议。 谢谢

Answer 1:

终于让我找到解决方案使用凌空库,它现在工作正常

  private void callApiWithJsonReqPost() {
        boolean failure = false;
        uAddress="133 Phùng Hưng, Cửa Đông, Hoàn Kiếm, Hà Nội, Vietnam";
       addressTag="work address";
        String callingURl="put your url here"

    JSONObject jsonObject=null;

    try {
         jsonObject=new JSONObject();
        jsonObject.put("address", uAddress);
        jsonObject.put("type", "insert");
        jsonObject.put("tag", addressTag);

    } catch (Exception e) {
        e.printStackTrace();
    }


    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
            callingURl, jsonObject,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d("new_address" ,"sons=="+response.toString());

                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("error", "Error: " + error.getMessage());

        }
    }) {

        /**
         * Passing some request headers
         * */
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }


    };

    // Adding request to request queue
    Singleton_volley.getInstance().addToRequestQueue(jsonObjReq,"1");


}


Answer 2:

params.add(new BasicNameValuePair("key",data)); 


JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);


Answer 3:

我写了一个库,用于分析和Android中产生JSON http://github.com/amirdew/JSON

例如:

 JSON generatedJsonObject = JSON.create(
                JSON.dic(
                        "someKey", "someValue",
                        "someArrayKey", JSON.array(
                                "first",
                                1,
                                2,
                                JSON.dic(
                                        "emptyArrayKey", JSON.array()
                                )
                        )
                )
        );


  String jsonString = generatedJsonObject.toString();

结果:

{
  "someKey": "someValue",
  "someArrayKey": [
    "first",
    1,
    2,
    {
      "emptyArrayKey": []
    }
  ]
}


文章来源: how to post parameters as a json in android while calling any api