I want to send a simple POST request in Android with a body equaling this :
[
{
"value": 1
}
]
I tried to use Volley library in Android, and this is my code :
// the jsonArray that I want to POST
String json = "[{\"value\": 1}]";
JSONArray jsonBody = null;
try {
jsonBody = new JSONArray(json);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONArray finalJsonBody = jsonBody;
// starting the request
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request =
new JsonObjectRequest(com.android.volley.Request.Method.POST,"https://...",null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("mytag", "Response is: " + response);}},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Mytag", "error");}}) {
@Override
protected Map<String,String> getParams() {
// the problem is here...
return (Map<String, String>) finalJsonBody;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
// I put all my headers here like the following one :
params.put("Content-Type", "application/json");
return params;}};
queue.add(request);
The problem is that the getParams method only accepts a Map object since I want to send a JSONArray. So, I'm obliged to use a cast, which generate an error then...
I don't know how can I fix that Thank you
You can refer to my following sample code:
UPDATE for your pastebin link:
Because the server responses a
JSONArray
, I useJsonArrayRequest
instead ofJsonObjectRequest
. And no need to overridegetBody
anymore.My code works for both Google's official volley libray and mcxiaoke's library
If you want to use Google's library, after you git clone as Google documentation, copy android folder from
\src\main\java\com
(of Volley project that you cloned) to\app\src\main\java\com
of your project as the following screenshot:The
build.gradle
should contain the followingIf your project uses mcxiaoke's library, the
build.gradle
will look like the following (pay attention todependencies
):I suggest that you will create 2 new sample projects, then one will use Google's library, the other will use mcxiaoke's library.
END OF UPDATE
The following screenshot is what server-side web service received: