To send a POST request with JSON payload using Apache HttpClient, you can follow the steps below:
- Create an instance of
HttpClient
usingHttpClientBuilder
. - Create an instance of
HttpPost
with the target URL. - Create a
StringEntity
with the JSON payload and set it as the entity of theHttpPost
request. - Set the content type header to
application/json
usingsetHeader
. - Execute the request using
httpClient.execute(httpPost)
. - Handle the response as needed.
Apache HttpClient Post Example code:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientPostJsonExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
try {
// Specify the URL endpoint for the POST request
HttpPost httpPost = new HttpPost("http://example.com/api/resource");
// Set the JSON payload
String jsonPayload = "{\"name\":\"John\", \"age\":30}";
StringEntity stringEntity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
// Execute the request
HttpResponse response = httpClient.execute(httpPost);
// Get the response status code
int statusCode = response.getStatusLine().getStatusCode();
// Get the response body
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
// Close the response entity
EntityUtils.consume(responseEntity);
// Handle the response
System.out.println("Response Code: " + statusCode);
System.out.println("Response Body: " + responseBody);
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the HttpClient instance
httpClient.getConnectionManager().shutdown();
}
}
}
In this example, we create an HttpPost
instance with the target URL and set the JSON payload as a StringEntity
. The StringEntity
is created with the content type application/json
using ContentType.APPLICATION_JSON
.
After executing the request, we retrieve the response status code and body as before.
Remember to include the Apache HttpClient library in your project dependencies before running the code.
Thanks for Reading..