apache httpclient http post request
www.igiftdiea.com
To make an HTTP POST request using Apache HttpClient, follow these steps:
- Create an instance of HttpClient:
HttpClient httpClient = HttpClientBuilder.create().build();
- Create an instance of HttpPost with the URL to be posted to:
HttpPost httpPost = new HttpPost("http://www.example.com");
- Add any parameters or headers to the request as needed:
httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity("{\"key\":\"value\"}"));
- Execute the request and get the response:
HttpResponse httpResponse = httpClient.execute(httpPost);
- Extract the response body as a String:
String responseBody = EntityUtils.toString(httpResponse.getEntity());
- Release the connection:
EntityUtils.consume(httpResponse.getEntity());
Here's an example that puts it all together:
import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.HttpResponse; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://www.example.com"); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity("{\"key\":\"value\"}")); HttpResponse httpResponse = httpClient.execute(httpPost); String responseBody = EntityUtils.toString(httpResponse.getEntity()); System.out.println(responseBody); EntityUtils.consume(httpResponse.getEntity()); } }
This example creates an HttpClient instance, creates an HttpPost request for the URL "http://www.example.com", adds a JSON payload to the request, executes the request using the HttpClient's execute() method, extracts the response body as a String, prints it to the console, and releases the connection. Note that you'll need to handle any exceptions that might be thrown by these methods.