0

Suppose my link and parameters are such as

url :https/example.com/folder/something
parameters  : JsonObject. such as
{
    "foldername" : "imageFolder",
    "jsonArray"  : ["abc","sdsf","sfsd"],
    "location"   : "Dhaka"
}

How to send JsonObject using POST method via url in Android? Please help me anybody.

Onik
  • 19,396
  • 14
  • 68
  • 91
kablu
  • 629
  • 1
  • 7
  • 26
  • possible duplicate of [How to pass a JSON Object in HTTPURLConnection](http://stackoverflow.com/questions/8803006/how-to-pass-a-json-object-in-httpurlconnection) – josephus May 05 '14 at 04:01

1 Answers1

0

The documentation for HttpURLConnection already has an example of how to POST data to a server. I've elaborated on it a little to show creation of the JSONObject and writing the data to the OutputStream.

try {
    // Create parameters JSONObject
    String[] jsonArray = new String[] { "abc", "sdsf", "sfsd" };
    JSONObject parameters = new JSONObject();
    parameters.put("foldername", "imageFolder");
    parameters.put("jsonArray", new JSONArray(Arrays.asList(jsonArray)));
    parameters.put("location", "Dhaka");

    // Open connection to URL and perform POST request.
    URL url = new URL("https://example.com/folder/something");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoOutput(true); // Set Http method to POST
    urlConnection.setChunkedStreamingMode(0); // Use default chunk size

    // Write serialized JSON data to output stream.
    OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
    writer.write(parameters.toString());

    // Close streams and disconnect.
    writer.close();
    out.close();
    urlConnection.disconnect();

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (JSONException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
savanto
  • 4,470
  • 23
  • 40