Category Archives: API Automation

Sending Http post request with simple JSONObject looks easy for us..
but when it comes to send post request with JSONObject which includes multiple JSONArrays, we face it little bit tough..

I faced it tough when I came across a situation where i need to send post request with JSONObject which includes JSONObject and Multiple JSONArrays

So I thought this example would help us when we come across sending this type of Httppost request..

The below is  the JSONObject including JSONArrays and which we are using in sending HTTPPost

"id": 1,
"name": {
"first": "abc",
"last": "pqr"
"contact": [
"type": "phone/home",
"ref": "111-111-1234"
"type": "phone/work",
"ref": "222-222-2222"
"address": [
"type": "permanent",
"": "111/121"
"type": "temporary",
"": "222/121"
"city": "Hyderabad",
"Company": "NBOS Technologies"

Sending the above JSONObject as a HTTPpost request

JSONObject mainObject = new JSONObject();

// For the name Object
JSONObject nameObject = new JSONObject();

// As homeContact/workContact represents as JSONObject..
JSONObject homeContact = new JSONObject();
homeContact.put("type", "phone/home").put("ref","111-111-1234");

JSONObject workContact = new JSONObject();
workContact.put("type", "phone/work").put("ref","222-222-2222");

// As tempAddress/permAddress represents as JSONObject
JSONObject tempAddress = new JSONObject();
tempAddress.put("type", "temporary").put( "": "111/121");

JSONObject permAddress = new JSONObject();
permAdress.put("type", "permanent").put( "": "222/121");

//As we have "Contact" which represents as JSONArray.. we are adding both homeContact and workContact in an array
JSONArray allContacts = new JSONArray();

//As we have "address" which represents as JSON Array.. we are adding both tempAddress and permAddress in an array..
JSONArray allAdresses = new JSONArray();

// the mainObject is the main JSONObject which includes JSONObject, JSONArrays.. we are adding all into one JSONObject
.put("company","NBOS Technologies");

CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost("Give the URl");
// while setting Entity, the mainObject must be converted to string
httpPost.setEntity(new StringEntity(mainObject.toString()));
httpPost.addHeader(new BasicHeader("Accept", "application/json"));
response = httpclient.execute(httpPost);
int serverCode = response.getStatusLine().getStatusCode();

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String line = "";

// Go through results
while ((line = rd.readLine()) != null) {
String sResult = (sResult + line);


“sResult” contains the HTTPResponse for the HTTPRequest you have sent for..