The following code snippet show you how to send POST request with a JSON body using HttpClient. The payload in this example is a user information containing id
, first_name
and a last_name
. We placed the payload in an object called StringEntity
and also set its content type to ContentType.APPLICATION_FORM_URLENCODED
.
On the other end called by this post request, data can be read for instance in a Java Servlet using the HttpServletRequest.getParameter()
method. For example to read the JSON body send below we can call request.getParameter("data")
. This will give us the payload sent using the HttpClient Post request.
Let’s jump into the code snippet below:
package org.kodejava.apache.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
public class HttpPostJsonExample {
public static void main(String[] args) {
String payload = """
data={
"username": "admin",
"first_name": "System",
"last_name": "Administrator"
}
""";
StringEntity entity = new StringEntity(payload,
ContentType.APPLICATION_FORM_URLENCODED);
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost("http://localhost:8080/register");
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
May I know how to get the body of the JSON response?
Hi Abhishek,
You can get the response body as JSON string using the following code. The
IOUtils
come from the Apache Commons IO library.How can we retrieve POST request body JSON in REST API and validate it?
If I have a json file, how can I pass the file itself while making the HTTP POST request ?
Hi Debarchan,
Is the following example is what you need? How do I do multipart upload using HttpClient?