简体   繁体   中英

Android Volley POST Parameters

I need to call an api that expects a string array as a POST parameter. So for an example of an API definition:

POST api/names

POST parameter expected is an array of names and some other attributes like below:

{ names: [ "John", "Bill" ], department: "Engineering" }

I am currently using a custom Volley framework as described in the Android documentation but it seems like the parameters from Volley can only be passed as a Map of (String, String as key and value). I already have the array from my Android app, ready to be passed as a post parameter but this Volley expects a String.

I tried to convert my array using Arrays.toString(myStringArray) and passed it like below but it does not work.

String[] namesArray = new String[1];
namesArray[0] = "Bill";

Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("department", "Computer Science");
mapParams.put("names", Arrays.toString(namesArray));

// Then call the Volley here passing the mapParams. 

How can I call the api that expects a String of array when I can only use a String from Volley?

I will give you full code to post JsonObject on volley, through POST method.

JSONObject js = new JSONObject();
    try {
        js.put("genderType", "MALE");
        }

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

    String url = "LINK TO POST/";

    // Make request for JSONObject
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(
            Request.Method.POST, url, js,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.e(TAG, "Response_Code from Volley" + "\n" + response.toString() + " i am king");
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e(TAG, "Error: " + error.getMessage());
            NetworkResponse response = error.networkResponse;
            if (error instanceof ServerError && response != null) {
                try {
                    String res = new String(response.data,
                            HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                    // Now you can use any deserializer to make sense of data
                    Log.e(TAG, "onErrorResponse: of uploadUser" + res);
                    //   JSONObject obj = new JSONObject(res);
                } catch (UnsupportedEncodingException e1) {
                    // Couldn't properly decode data to string
                    e1.printStackTrace();
                }
            }
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
        }
    };
    Log.e(TAG, "uploadUser:  near volley new request ");
    // Adding request to request queue
    Volley.newRequestQueue(this).add(jsonObjReq);

}

Put anything you need in the js object with key and its values

Use JsonObjectRequest and simply pass a JSONObject . There's a full example here

public void makePostRequest(final Map<String,String> myMap,String MEDIA_URL,final VolleyResponse callback)
                        {
                             VolleySingleton VS;
                            Log.e("URL",MEDIA_URL);
                            VS=VS.getInstance();
                            RequestQueue rq=VS.getRequestQueue();

                            StringRequest stringRequest = new StringRequest(Request.Method.POST,MEDIA_URL,
                                    new Response.Listener<String>() {
                                        @Override
                                        public void onResponse(String s) {
                                            callback.onSuccess(s);
                                        }
                                    },
                                    new Response.ErrorListener() {
                                        @Override
                                        public void onErrorResponse(VolleyError volleyError) {
                                                            callback.onError();
                                                }
                                    }){
                                @Override
                                protected Map<String, String> getParams() throws AuthFailureError {

                                    Map<String,String> params = new Hashtable<String, String>();

                                    Iterator<Map.Entry<String, String>> iterator = myMap.entrySet().iterator();
                                    while(iterator.hasNext()) {
                                        Map.Entry<String,String> pairs = (Map.Entry<String,String>)iterator.next();
                                        String value =  pairs.getValue();
                                        String key = pairs.getKey();
                                        params.put(key,value);
                                        Log.e("Key","Value"+value);
                                    }
                                    return params;
                                }
                            };

                            //Creating a Request Queue
                            // RequestQueue requestQueue = Volley.newRequestQueue(this);
                            DefaultRetryPolicy  retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                            stringRequest.setRetryPolicy(retryPolicy);
                            //Adding request to the queue
                           rq.add(stringRequest);

                        }

Where the VolleyResponse is a simple custom interface like this

public interface VolleyResponse {
void onSuccess(String resp);
void onError();

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM