Apache HttpClient GET HTTP Request Example

In this quick article, we will discuss step by step how to use Apache HttpClient 4.5 to make an Http GET request. The HTTP GET method represents a representation of the specified resource. This could be as simple as getting an HTML page, or getting resources formatted in JSON, XML or etc. Requests using HTTP GET Request methods should be Idempotent, meaning: these should only retrieve data and should have no other effects.
HttpClient supports out of the box all HTTP methods defined in the HTTP/1.1 specification: GET, HEAD, POST, PUT, DELETE, TRACE, and OPTIONS. There is a specific class for each method type.: HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions.
In this example, we will use HttpGet class to handle GET HTTP Method.
Check out Apache HttpClient POST HTTP Request Example

Using the Apache HttpClient - Add Dependency

The Apache HttpClient library allows handling HTTP requests. To use this library add a dependency to your Maven or Gradle build file. You find the latest version here: https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
We use maven to manage our dependencies and are using Apache HttpClient version 4.5. Add the following dependency to your project in order to make HTTP POST request method.
<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.5</version>
</dependency>

Development Steps

Let's create a step by step example to make an HTTP GET request using HttpClient.

1. Create instance of CloseableHttpClient using helper class HttpClients.

CloseableHttpClient httpclient = HttpClients.createDefault()
The HttpClients.createDefault() method creates CloseableHttpClient instance with default configuration.

2. Create a basic GET request

 HttpGet httpget = new HttpGet("http://httpbin.org/get");

3. Create a custom response handler

ResponseHandler < String > responseHandler = response - > {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

4. Send basic GET request via execute() method

String responseBody = httpclient.execute(httpget, responseHandler);

5. Get the Status Code of the HTTP Response

int status = response.getStatusLine().getStatusCode();

6. Get a response entity

HttpEntity entity = response.getEntity();

HttpClient HTTP GET Request Method Example

In the following example, we retrieve a resource from http://httpbin.org/get. This resource returns a JSON object which we’ll simply print to the console. In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.
package com.javadevelopersguide.httpclient.examples;

import org.apache.http.HttpEntity;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

/**
 * This example demonstrates the use of {@link HttpGet} request method.
 * @author Ramesh Fadatare
 */
public class HttpGetRequestMethodExample {

    public static void main(String...args) throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //HTTP GET method
            HttpGet httpget = new HttpGet("http://httpbin.org/get");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}
Output:
Executing request GET http://httpbin.org/get HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
  }, 
  "origin": "49.35.12.218", 
  "url": "http://httpbin.org/get"
}

More Examples

Let's discuss how to use HttpClient in real-time projects. Consider we have deployed Spring boot Restful CRUD APIs. Check out this article - Spring Boot 2 + hibernate 5 + CRUD REST API Tutorial.
Let's write a Rest client to get JSON from below Rest services
package com.javadevelopersguide.httpclient.examples;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of {@link HttpGet} request method.
 * @author Ramesh Fadatare
 */
public class HttpGetRequestMethodExample {

    public static void main(String[] args) throws IOException {
        getUsers();
        getUserById();
    }

    private static void getUsers() throws ClientProtocolException, IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //HTTP GET method
            HttpGet httpget = new HttpGet("http://localhost:8080/api/v1/users");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }

    private static void getUserById() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //HTTP GET method
            HttpGet httpget = new HttpGet("http://localhost:8080/api/v1/users/5");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}
Output:
Executing request GET http://localhost:8080/api/v1/users HTTP/1.1
----------------------------------------
[{"id":5,"firstName":"Ram","lastName":"Jadhav","emailId":"[email protected]","createdAt":"2018-09-11T11:19:56.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-11T11:26:31.000+0000","updatedby":"Ramesh"},
{"id":6,"firstName":"Ramesh","lastName":"fadatare","emailId":"[email protected]","createdAt":"2018-09-11T11:20:07.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-11T11:20:07.000+0000","updatedby":"Ramesh"},
{"id":17,"firstName":"John","lastName":"Cena","emailId":"[email protected]","createdAt":"2018-09-19T08:28:10.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-19T08:28:10.000+0000","updatedby":"Ramesh"},
{"id":18,"firstName":"John","lastName":"Cena","emailId":"[email protected]","createdAt":"2018-09-19T08:29:29.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-19T08:29:29.000+0000","updatedby":"Ramesh"}]
Executing request GET http://localhost:8080/api/v1/users/5 HTTP/1.1
----------------------------------------
{"id":5,"firstName":"Ram","lastName":"Jadhav","emailId":"[email protected]","createdAt":"2018-09-11T11:19:56.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-11T11:26:31.000+0000","updatedby":"Ramesh"}

References

Comments