apache httpclient http post request

www.igift‮di‬ea.com

To make an HTTP POST request using Apache HttpClient, follow these steps:

  1. Create an instance of HttpClient:
HttpClient httpClient = HttpClientBuilder.create().build();
  1. Create an instance of HttpPost with the URL to be posted to:
HttpPost httpPost = new HttpPost("http://www.example.com");
  1. Add any parameters or headers to the request as needed:
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity("{\"key\":\"value\"}"));
  1. Execute the request and get the response:
HttpResponse httpResponse = httpClient.execute(httpPost);
  1. Extract the response body as a String:
String responseBody = EntityUtils.toString(httpResponse.getEntity());
  1. 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.