The general process for using HttpClient consists of a number of steps:

  • Create an instance of HttpClient.
  • Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
  • Tell HttpClient to execute the method.
  • Read the response.
  • Release the connection.
  • Deal with the response.

The following code shows how these steps can be implemented:

 import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;


public class HttpClientTutorial {
    private static String url = "";
    public static void main(String[] args) {
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();
        // Create a method instance.
        GetMethod method = new GetMethod(url);
        // Provide custom retry handler is necessary
                new DefaultHttpMethodRetryHandler(3, false));
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + 
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            // Deal with the response.
            // Use caution: ensure correct character encoding and 
            // is not binary data
            System.out.println(new String(responseBody));
        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
        } finally {
            // Release the connection.

Source: Apache HttpClient