Up until now, we have already covered configuring the HttpClient library and sending a GET Request using HttpClient in Java. If you haven’t checked that, go for it by clicking this link. Now, in this example, we are going to see “How to send a POST request with JSON as request body using Apache HttpClient by utilizing HttpPost method?”.
Simple example of POST Request with JSON using Apache HttpClient...!!! Share on X
In this tutorial, we are going to cover below topics:
- What is HTTP POST Request?
- How to send POST request with JSON using Apache HttpClient?
Check out: POST REQUEST using another popular API testing Framework – REST ASSURED
Let’s begin:
1. What is HTTP POST Request?
POST is one of the most common methods of HTTP which is used to send data to a server to create/update the resource. Data sent to the server is in the form of either Request Body / Request Parameters which is basically used to create or update the resource on the server.
Some key points of POST requests:
- POST requests parameters doesn’t store in the browser history
- POST requests are used to send data to the server to create or update the resource
- POST requests cannot be cached
- POST requests are secure as compared to GET because parameters/data doesn’t store in browser history
- POST requests parameter data is unlimited as there are no length restrictions
- POST requests cannot be bookmarked
- POST requests allow ASCII characters
- POST requests are difficult to hack
2. How to send POST request with JSON using Apache HttpClient?
In this tutorial, we will test the ‘Dummy Sample Rest API’ which is available here. This page contains Fake Online REST API for the testing purposes which are performing various CRUD operations.
Let’s take an example of one of the API POST endpoint available at the above-mentioned website which is ‘/create’. The full-service URL with endpoint is ‘http://dummy.restapiexample.com/api/v1/create‘.
At the above resource URL, we are going to submit data in the form of JSON to create an employee.
JSON Request Body:
1 2 3 4 5 | { "name":"tammy133", "salary":"5000", "age":"20" } |
Here is the code to send the POST request (containing request body in JSON format) to the above mentioned REST API Service Endpoint:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.testng.annotations.Test; /** * This class shows how to send a POST Request with JSON using 'HttpPost' method of Apache HttpClient library. * @author Deepak Verma */ public class Post_Request_Apache_HttpClient { @Test public void createEmployee() throws ClientProtocolException, IOException { String postEndpoint = "http://dummy.restapiexample.com/api/v1/create"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(postEndpoint); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); String inputJson = "{\n" + " \"name\": \"tammy133\",\n" + " \"salary\": \"5000\",\n" + " \"age\": \"20\"\n" + "}"; StringEntity stringEntity = new StringEntity(inputJson); httpPost.setEntity(stringEntity); System.out.println("Executing request " + httpPost.getRequestLine()); HttpResponse response = httpclient.execute(httpPost); BufferedReader br = new BufferedReader( new InputStreamReader((response.getEntity().getContent()))); //Throw runtime exception if status code isn't 200 if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } //Create the StringBuffer object and store the response into it. StringBuffer result = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { System.out.println("Response : \n"+result.append(line)); } //Lets validate if a text 'employee_salary' is present in the response System.out.println("Does Reponse contains 'employee_salary'? :" + result.toString().contains("employee_salary")); } } |
Let’s try to understand the code:
1. Specify the URL and set up CloseableHttpClient object
1 2 3 | String postEndpoint = "http://dummy.restapiexample.com/api/v1/create"; CloseableHttpClient httpclient = HttpClients.createDefault(); |
2. Create a basic Post Request and pass the resource URI to it and also assign headers to this post object
1 2 3 4 5 | HttpPost httpPost = new HttpPost(postEndpoint); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); |
3. Supply the json request into the StringEntity object and assign it to the post object.
1 2 3 | StringEntity stringEntity = new StringEntity(inputJson); httpPost.setEntity(stringEntity); |
4. Submit the Request using HttpPost -> Execute method
1 | HttpResponse response = httpclient.execute(httpPost); |
5. Create a BufferedReader object and store the raw Response content into it.
1 | BufferedReader br = new BufferedReader( new InputStreamReader((response.<wbr />getEntity().getContent()))); |
6. Throw runtime exception if status code isn’t 200
1 2 3 | if (response.getStatusLine().<wbr />getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().<wbr />getStatusCode()); } |
7. Create the StringBuffer object and store the response into it.
1 2 3 4 5 6 7 | StringBuffer result = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { System.out.println("Response : \n"+result.append(line)); } |
8. Finally, Lets validate if a text ’employee_salary’ is present in the response
1 | result.toString().contains("<wbr />employee_salary") |
Eclipse Console Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | [RemoteTestNG] detected TestNG version 6.14.3 Executing request POST http://dummy.restapiexample.com/api/v1/create HTTP/1.1 Response : {"name":"tammy133","salary":"5000","age":"20","id":"1659"} Does Reponse contains 'employee_salary'? :false PASSED: createEmployee =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== |
That’s it, it’s that simple to make a POST Request with JSON body using Apache HttpClient: ?
Simple example of POST Request with JSON using Apache HttpClient...!!! Share on X
If you like this post , please check out my other useful blog posts:
Other Useful References:
Hi, Bro.
Nice code, clean and functional.
Thanks.
Thank you so much Charles.
I am glad it helped.
Thanks