How do I perform HTTP GET method?

Below is an example using Commons HttpClient library to retrieve information from a website using HTTP GET method. The response will be returned as string by the HttpMethod.getResponseBodyAsString() method.

package org.kodejava.example.commons.httpclient;
 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
 
import java.io.IOException;
 
public class HttpGetDemo {
    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("http://www.kodejava.org");
 
        try {
            client.executeMethod(method);
 
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                String response = method.getResponseBodyAsString();
                System.out.println("Response = " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }
}

Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.