Tutorial

Apache HttpClient Example - CloseableHttpClient

Published on August 3, 2022
Default avatar

By Pankaj

Apache HttpClient Example - CloseableHttpClient

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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

apache httpclient, httpclient example, httpclient java, apache httpclient example, closeablehttpclient 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.

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.4</version>
</dependency>

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, HttpClient example 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.

package com.journaldev.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class ApacheHttpClientExample {

	private static final String USER_AGENT = "Mozilla/5.0";

	private static final String GET_URL = "https://localhost:9090/SpringMVCExample";

	private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";

	public static void main(String[] args) throws IOException {
		sendGET();
		System.out.println("GET DONE");
		sendPOST();
		System.out.println("POST DONE");
	}

	private static void sendGET() throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(GET_URL);
		httpGet.addHeader("User-Agent", USER_AGENT);
		CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

		System.out.println("GET Response Status:: "
				+ httpResponse.getStatusLine().getStatusCode());

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		// print result
		System.out.println(response.toString());
		httpClient.close();
	}

	private static void sendPOST() throws IOException {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(POST_URL);
		httpPost.addHeader("User-Agent", USER_AGENT);

		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));

		HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
		httpPost.setEntity(postParams);

		CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

		System.out.println("POST Response Status:: "
				+ httpResponse.getStatusLine().getStatusCode());

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		// print result
		System.out.println(response.toString());
		httpClient.close();

	}

}

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

GET Response Status:: 200
<html><head>	<title>Home</title></head><body><h1>	Hello world!  </h1><P>  The time on the server is March 7, 2015 1:01:22 AM IST. </P></body></html>
GET DONE
POST Response Status:: 200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj Kumar</h3></body></html>
POST DONE

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 7, 2021

The formatting of this post is incredibly difficult to read. The outline just above the code doesn’t provide any value to this post and I would highly recommend removing it because it’s distracting. You’re also using Autocloseable’s, but you’re not using them the way they’re designed to be used (see try-with-resources). There are a number of improvements I would suggest making to this post.

- Sean

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    July 29, 2020

    How come there is no example of sending request body in POST mapping call. I think we need to convert object to string & set it in setEntity using StringEntity.

    - Satish

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 24, 2020

      Hi, I am getting NoSuchFieldException : INSTANCE while using this code. Google says there must be another version of the libraries but it is not.

      - Sukriti

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 13, 2017

        FYI: HttpEntity postParams = new UrlEncodedFormEntity(urlParameters); maybe we need to utf-8 encoding for post parameters, then we can code like this: HttpEntity postParams = new UrlEncodedFormEntity(urlParameters, “UTF-8”);

        - Danny

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 26, 2017

          It works but it doesn’t redirect to the URL entered how to make it redirect to to the URL that was entered

          - Kagabo Cedric

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 6, 2017

            Hi can anybody tell me the reason behind using this CloseableHttpClient instead of using HttpClient.? Is there any major difference between these two? Please explain me reason for this. Thanks, Sailendra Jena

            - Sailendra Jena

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              January 10, 2017

              Dear sir, i want to know the difference between HttpClient and HttpUrlConnection.

              - saikrishna rao

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                September 5, 2016

                @Pankaj I added the the dependency to my pom.xml however whenever I try to call my sendGet() method I get a NoClassDefFound error for org.apache.http.client.HttpClient. Why is this happening?

                - Zach

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 21, 2016

                  hI ,how to set timeout?

                  - mangesh rode

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 7, 2015

                    I’m seeing the same error as Varun Sengar.

                    - Jane Norrie

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel