how to post JSON ARRAY data to server in Android

Faiz Anwar picture Faiz Anwar · Mar 10, 2014 · Viewed 15.8k times · Source

I want to send below JSON data to server and read the response in android. Below is the Json data.

{
    "class": "OrderItemListDto",
    "orderItemList": [
        {
            "class": "OrderItemDto",
            "orderId": 24,
            "itemId": 1,
            "quantity": 2,
            "status": "NEW",
            "sRequest": "none"
        },
        {
            "class": "OrderItemDto",
            "orderId": 24,
            "itemId": 2,
            "quantity": 2,
            "status": "NEW",
            "sRequest": "none"
        }
    ]
}

Here May be data will be increased.

Answer

Sergey  Pekar picture Sergey Pekar · Mar 11, 2014

Check this code

JSONArray json = //your array;
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://your_url");

try {

    StringEntity se = new StringEntity(json.toString());

    httpPost.setEntity(se);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");


    HttpResponse response = httpClient.execute(httpPost, httpContext); //execute your request and parse response
    HttpEntity entity = response.getEntity();

    String jsonString = EntityUtils.toString(entity); //if response in JSON format

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