2 Minutes To Code (β Version)

Apache Commons Http Client - 2 minute tutorial

Basic usage : How to make a GET http request

This example shows how to make an HTTP get request to an http server.

You need to create an org.apache.commons.httpclient.HttpClient object and an org.apache.commons.httpclient.methods.GetMethod objectpassing it the url to hit. Then call then executeMethod(...) method of HttpClient passing it the GetMethod object as argument.

The response can be read by using the getResponseBodyAsString method of GetMethod object.

The getResponseBodyAsString is not efficient as it will store the complete response on jvm's heap, which can be troublesome if the response is big. Additionally, it converts the bytes received in response to string, which can corrupt the data if it is a binary file or a text file not encoded with the jvm's default character set.

The next example shows an efficient way to read http response.
package com.techfundaes.httpBag;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class SimpleGet
{
	public static void main(String[] args)
	{
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod("http://www.techfundaes.com/test.do");
		try
		{
			httpClient.executeMethod(getMethod);
			System.out.println("responseString:"+getMethod.getResponseBodyAsString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			getMethod.releaseConnection();
		}
	}
}