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

A programmer, a slow runner, a recreational open water 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.

Leave a Reply