This web page publishes a Java HTTP POST client that uses the Apache Commons HttpClient classes (Commons is a subproject of the Apache Jakarta project). The HTTP POST client sends POST messages to a defined URL and reads the response. This POST client not only handles the HTTP transaction, it also handles timeout in the case where the HTTP transaction hangs on an unresponsive URL (an unresponsive IP address, for example).
Before I learned about the Apache Commons HttpClient classes, I wrote a class that I named SynchronousHttp to handle HTTP POST operations and return a result (for an example of a class that uses the SynchronousHttp class see EchoClient). The SynchronousHttp class uses the standard Java libraries. The Apache Commons HttpClient class allow the details of these classes to be abstracted so writing a class like SynchronousHttp is unnecessary. The HttpClient libraries also provide support for handling HTTP timeouts.
To compile and run the HTTP POST client code you will need to download the Apache Commons HttpClient and Logging ".jar" files. You should make sure that these .jar files are defined in your CLASS_PATH environment variable. These Apache .jar files can be obtained from:
Apache Jakarta Commons HttpClient. The .jar file is
The Commons Logging code is used by the HttpClient code.
I've written three classes to show how to use some of the HttpClient classes:
The HttpPostMessage class hides most of the details of the HTTP post operation. The constructor is passed the URL that the POST messages will be sent to and a time out (in milliseconds). The postMessage method is passed the message (a String) that will be sent in the HTTP POST.
The HttpExecute class extends the class java.lang.Runnable. The constructor is passed the URL. Once the object has been created, it can be reused. However, the setMessage() method must be called before each POST operation, even if the same message is being sent. The HttpExecute object is passed to the Apache Commons HttpClient TimeoutController execute method, along with the timeout value. The execute method calls HttpExecute's run() method, which performs the POST operation. If the POST hangs, it will be terminated by the TimeoutController and an exception will be generated.
The HttpClient class contains the main method. The HttpClient is designed to send messages to the EchoServlet (see Notes on Resin and Java Servlets). The main method sends arguments from the command line to the EchoServlet which appends a time stamp to the string and returns it.
Ian Kaplan, October 2004
back to Java page