How do I execute Http Get request?

Below is an example using HttpClient library to retrieve the content of a website using Http Get request. We start by creating an instance of DefaultHttpClient 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 the website 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.example.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

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) {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://www.kodejava.org");

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

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply