How do I execute HTTP Get request?

Below is an example using HttpClient library to retrieve the response of HTTP GET request. We start by creating an instance of CloseableHttpClient class. We then define an HTTP GET request by create an instance of HttpGet class and specify the Url of a website we are going to retrieve.

To execute the request we call the HttpClient.execute() method and pass the HttpGet as the arguments. This execution return an HttpResponse object. From this response object we can read the content of response by accessing the getEntity().getContent() which will give us an InputStream to the content.

For more detail let’s see the code snippet below:

package org.kodejava.apache.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HttpGetExample {
    public static void main(String[] args) {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            HttpGet request = new HttpGet("https://httpbin.org/get?id=1");

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                try (InputStream stream = entity.getContent()) {
                    BufferedReader reader =
                            new BufferedReader(new InputStreamReader(stream));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

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

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.