The following code snippet will show you how to send an HTTP post request using the Apache HttpComponents. We will send a post request to https://httpbin.org/post`, with some parameters to the request using the
NameValuePair` object.
To pass these parameters to the HTTP post request we create an instance of UrlEncodedFormEntity
and pass a list of NameValuePair
as the arguments. And before executing the request we set this entity object to the HttpPost.setEntity()
method.
Let’s see the code below:
package org.kodejava.apache.http;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class HttpPostExample {
public static void main(String[] args) {
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("https://httpbin.org/post");
// Create some NameValuePair for HttpPost parameters
List<NameValuePair> arguments = new ArrayList<>(3);
arguments.add(new BasicNameValuePair("username", "admin"));
arguments.add(new BasicNameValuePair("firstName", "System"));
arguments.add(new BasicNameValuePair("lastName", "Administrator"));
try {
post.setEntity(new UrlEncodedFormEntity(arguments));
HttpResponse response = client.execute(post);
// Print out the response message
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=org/apache/httpcomponents/httpclient/4.5.13/httpclient-4.5.13.jar -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023
How would I send a body (in my case JSON data)?
You can try the code snippet below to send JSON message.
If you are calling a servlet, you can get the JSON string by calling
request.getParameter("data");
Hi, how i could send a Body(like this example) and also params (like your article) together? Thank you a lot!
How do I send a file as a http body via HTTP POST request?.
Hi Rahul, take a look at this example: How do I do multipart upload using HttpClient?.
{"indexArray":["Bpd","Qwg"]}
this is Json Body. How do i send it via POST request?Hi Shweta,
You can check this example: How do I send POST request with a JSON body using the HttpClient?