Apache HttpClient Example - CloseableHttpClient

Apache HttpClient can be used to send HTTP requests from client code to server. In our last tutorial, we saw how to use HttpURLConnection to perform GET and POST HTTP request operations from java program itself. Today we will take the same example project but use Apache HttpClient to perform GET and POST request operations.

Apache HttpClient

For the sake of understanding the GET and POST request details, I would strongly suggest you to have a look at the earlier example too. Apache HttpClient is very widely used for sending HTTP requests from java program itself. If you are using Maven, then you can add below dependencies and it will include all other required dependencies for using Apache HttpClient.

However if you are not using Maven, then need to add following jars in your project build path for it to work.

  1. httpclient-4.4.jar
  2. httpcore-4.4.jar
  3. commons-logging-1.2.jar
  4. commons-codec-1.9.jar

If you are using some other version of Apache HttpClient and not using Maven, then just create a temporary Maven project to get the list of compatible jars, as shown in image below.

Apache-HttpClient-Maven-Dependencies

Now just copy the jars to your project lib directory, it will save you from any compatibility issues as well as it will save time in finding jars and downloading from internet.

Now that we have all the required dependencies, below are the steps for using Apache HttpClient to send GET and POST requests.

  1. Create instance of CloseableHttpClient using helper class HttpClients.
  2. Create HttpGet or HttpPost instance based on the HTTP request type.
  3. Use addHeader method to add required headers such as User-Agent, Accept-Encoding etc.
  4. For POST, create list of NameValuePair and add all the form parameters. Then set it to the HttpPost entity.
  5. Get CloseableHttpResponse by executing the HttpGet or HttpPost request.
  6. Get required details such as status code, error information, response html etc from the response.
  7. Finally close the apache HttpClient resource.

Below is the final program we have showing how to use Apache HttpClient for performing HTTP GET and POST requests in a java program itself.

When we run above program, we get similar output html as received in the browser.

That’s all for Apache HttpClient example, it contains a lot of utility methods that you can use. So I would suggest you to check them out for better understanding.

By admin

Leave a Reply