问题
I am new to Android development, I need to post parameters as a JSON while calling any API method.
I am passing as a array list:
List<NameValuePair> params = new ArrayList<NameValuePair>();
Please give any suggestions. Thank you
回答1:
finally i found solution using volley library, it's working fine now
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");
}
回答2:
params.add(new BasicNameValuePair("key",data));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
回答3:
I wrote a library for parsing and generating JSON in Android http://github.com/amirdew/JSON
for example:
JSON generatedJsonObject = JSON.create(
JSON.dic(
"someKey", "someValue",
"someArrayKey", JSON.array(
"first",
1,
2,
JSON.dic(
"emptyArrayKey", JSON.array()
)
)
)
);
String jsonString = generatedJsonObject.toString();
result:
{
"someKey": "someValue",
"someArrayKey": [
"first",
1,
2,
{
"emptyArrayKey": []
}
]
}
来源:https://stackoverflow.com/questions/41718146/how-to-post-parameters-as-a-json-in-android-while-calling-any-api