Search code examples
androidjsonandroid-volleyjsonobjectrequest

How to send JSONObject to server as form-data using Volley


I'm going to send a JsonObjectRequest to the server as form-data using Volley Library. I Checked similar questions. none of them covers my problem.

This is Postman ScreenShot of the exact request that I need:

Postman

This is My JSONObject named myKey which contains a JSONArray:

{
 "myArray":[
    {
    "code":"FA95",
    "id":"94"
    }
 ]
}

and this is my request method:

public static void getSomething(String url) {

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {
        @Override
        public byte[] getBody() {
            return super.getBody();
        }
    };

    request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    AppController.getInstance().addToRequestQueue(request);
}

Should I override getBody() or not? and what should it return exactly?


Solution

  • Here is the answer: https://stackoverflow.com/a/39718240/3024933

    You need to override the getParams() method and use StringRequest instead of JsonObjectRequest.