java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to perform HTTP GET method?

Below is an example using Commons HttpClient library to retrieve information from a website using HTTP GET method.

package com.javacoderanch.example.commons.httpclient;

import org.apache.commons.httpclient.*;
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.javacoderanch.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();
        }
    }
}