Search code examples
androidarraysjsonhttpurlconnectionurlconnection

How to send Json array as post params in android open URL connection


I have to make a post request with payload as in the format of Json array. I am using an open HTTP URL connection. I have codes to send a Json object as post params using url connection, but I don't know how to send a json array. Below shown is the code for open url post request for json object. Can anyone help me to sent Json array instead of json object?

 public String   sendPostRequest(String arg0, JSONObject postDataParams){

    try {

        URL url = new URL(arg0); // here is your URL path

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "Bearer Key");
        conn.setRequestProperty("Content-Type", "application/json");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));
        writer.flush();
        writer.close();
        os.close();

        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            BufferedReader in=new BufferedReader(new
                    InputStreamReader(
                    conn.getInputStream()));

            StringBuffer sb = new StringBuffer("");
            String line="";

            while((line = in.readLine()) != null) {

                sb.append(line);
                break;
            }

            in.close();
            return sb.toString();

        }
        else {
            return new String("false : "+responseCode);
        }
    }
    catch(Exception e){
        return new String("Exception: " + e.getMessage());
    }

}


// converting json object to encoded string

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}

Here is the format I want to post.

[
  {
     "name":"CHV",
     "serialNumber":"421",
     "mac":"00:0d:83:b1:c0:8e",

  },
  {
     "name":"CHV_0",
     "serialNumber":"431",
     "mac":"50:0d:83:b1:c0:8e",
     }
   ]

How can I alter my code to post the json array.


Solution

  • This sample for your reference

    String request = "your Url Here";
    
    URL url = new URL(request); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false); 
    connection.setRequestMethod("POST"); 
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty("Authorization", "Bearer Key");
    conn.setRequestProperty("Content-Type", "application/json");
    
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
    wr.writeBytes(otherParametersUrServiceNeed);
    
    
    JSONArray jsonArray=new JSONArray();
    JSONObject jsonParam = new JSONObject();
    jsonParam.put("ID", "25");
    jsonParam.put("description", "Real");
    jsonParam.put("enable", "true");
    jsonArray.put(jsonParam);
    
    wr.writeBytes(jsonArray.toString());
    
    wr.flush();
    wr.close();
    

    For more detail checkout here, here or here