The next time you’re building a Web-aware
application and the Java API isn’t enough, you may want to check
out Jakarta Commons’ HTTP Client. Using HTTP Client is
straightforward: Create an instance of HttpClient, create an
instance of the method type you want to use, and then execute the
method using the instance of HttpClient.

Below is an example of fetching a Web page and
dumping its content to standard out.

    HttpClient client = new
    GetMethod get = new


Now suppose that you need to use the basic
authentication mechanism to access a page. In this case, you need
to use the HTTP Client class UsernamePasswordCredentials. Here’s
the code to add to accomplish this:

upc =
UsernamePasswordCredentials(“foo”, “bar”);

    client.getState().setCredentials(null, null,


In the following code, we add a timeout
specification to the get method in case the page takes a long time
to load.


As the sample code illustrates, making use of
the features in HTTP Client is simple. If your application needs
HTTP access, then check out HTTP Client. It has more features than
the Web-aware classes in the Java API, and it’s easy to use. Take a
look for yourself and see if it suits your needs.

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

public class HttpClientTip {
    public static void main(String args[])
        try {
client = new HttpClient();
get = new GetMethod(“”);

upc =
UsernamePasswordCredentials(“foo”, “bar”);

null, upc);





        catch (IOException
e) {


Find out more about HTTP Client’s many
features, including HTTPS, multipart POSTs, and proxy support, by
visiting the Apache Jakarta
Project site

Delivered each Thursday, our free Java newsletter provides insight and hands-on tips you need to unlock the full potential of this programming language. Automatically sign up today!