简体   繁体   中英

How to pass an array to POST API?

In my Android application, I need to send an array as body (payload information) to a POST url.

In body, there are two params:

1. "env" : "dev"  
2. "dNumber" : tn("+1232323"); // here I need to send an array.

Edited question: I need to send phone as an array like ["123131","4545545"]

I pass the array as created a JSON array and convert to string and passed.

private String tn(String tn) {
    String json = "";
    try {
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(0, tn);
        json = jsonArray.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return json;
}

and full code is:

    try {
        URL url;
        HttpURLConnection urlConnection;
        url = new URL(makeCallUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Authorization", String.format("%s %s", "Basic", secretKey));
        urlConnection.setUseCaches(false);
        urlConnection.setDoOutput(true);
        urlConnection.connect();
        // Setup the body of the url
        JSONObject json = new JSONObject();

        json.put("env", "dev");
        json.put("destNumbers", tn("+123123"));

        // Write the body on the wire
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
        writer.write(json.toString());
        writer.flush();
        writer.close();

    } catch (IOException e) {
        Log.d(TAG, "IOException:" + e.getMessage());
        e.printStackTrace();
    }

If I try this, I got 400, Bad request exception. Please help me to pass an array to POST api

I solved my problem using JSONArray and pass the array.

        // creating json array
        JSONArray numberArray = new JSONArray();
        numberArray.put(0, tn);

        // send the array with payload
        JSONObject json = new JSONObject();
        json.put("env", "DEV");
        json.put("destNumbers", numberArray);

Now I get array as following: destNumbers = ["3434343","3434334]

Update your tn() method. Instead of returning String it should return JSONArray.

private JSONArray tn(String tn) {
JSONArray jsonArray = new JSONArray();
   try {
       jsonArray.put(0, tn);
   } catch (JSONException e) {
       e.printStackTrace();
   }
   return jsonArray ;
}

Although if still the 400 Bad request error occur than confirm and verify the request payload with your json.

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