Apache HttpClient GET request

In this article, we will explore how to execute an HTTP GET request using Apache HttpClient library with example programs.
Setup
For using HttpClient library, you need to add it to your project as per the build tool using below dependency

// GRADLE
implementation 'org.apache.httpcomponents:httpclient:4.5.14'

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

If you are not using any build tool, then directly add its jar file to the classpath.

Note: Post version 4.5.14, httpclient has moved to a different artifact.
So, if you have to use later dependency, then use below

// MAVEN
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.2.1</version>
</dependency>

// GRADLE
implementation 'org.apache.httpcomponents.client5:httpclient5:5.2.1'

To test our program, we need an endpoint URL. For this article, we will be using a fake web service URL https://jsonplaceholder.typicode.com/posts, which returns a list of posts in response to a GET request.

Steps
Following are the steps required to execute a GET request using Apache HttpClient.

1. Create a client.
A client is used to send HTTP requests to a URL. This URL is called endpoint URL or simply endpoint.

A client object in HttpClient is created using below syntax

CloseableHttpClient client = HttpClients.createDefault();

At some places, you will also find below code that creates an instance of HttpClient.

CloseableHttpClient client = HttpClientBuilder.create().build();

Both are the same since createDefault() internally calls the same code.
2. Create a request
To execute a request in HttpClient, we need an object of HttpUriRequest.
This is an interface which is implemented by classes that represent HTTP request types such as HttpGet and HttpPost for GET and POST requests respectively.

Since this article shows a GET request, we need to create an object of HttpGet as below

HttpGet request = new HttpGet(
                      "https://jsonplaceholder.typicode.com/posts");

Constructor of HttpGet accepts the endpoint URL from where data will be fetched.

3. Execute request
Once we have a client and a request, it can directly be executed using execute() method of client.

execute() accepts an object of HttpUriRequest, which we created in the last step and returns the response returned by the URL as an object of CloseableHttpResponse as below

CloseableHttpResponse response = client.execute(get);

4. Reading response
CloseableHttpResponse contains a getEntity() method which returns an HttpEntity object, that contains the actual response.

HttpEntity has a getContent() method which returns a java InputStream containing the response.
This Inputstream can be used to read the response using BufferedReader or can be directly converted to a string.

HttpClient GET example
Below is a complete example of executing a GET request with HttpClient using the steps outlined above.

// create client
CloseableHttpClient client = HttpClients.createDefault();
// create request object
HttpGet get = new HttpGet(
                   "https://jsonplaceholder.typicode.com/posts");
try {
  // get response
  CloseableHttpResponse response = client.execute(get);
  // inputstream to bufferedread
  BufferedReader br = new BufferedReader(
                          new InputStreamReader(
          response.getEntity().getContent()));
  String line = null;
  // read response
  while( (line = br.readLine())!=null) {
    System.out.println(line);
  }
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

This is a trimmed response received using above code

[
{
“userId”: 1,
“id”: 1,
“title”: “sunt aut facere repellat provident occaecati excepturi optio reprehenderit”,
“body”: “quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto”
},

]

Hope the article was useful.