import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.PostMethod; /** \file * * Oct 23, 2004 * * Copyright Ian Kaplan 2004, Bear Products International * * You may use this code for any purpose, without restriction, * including in proprietary code for which you charge a fee. * In using this code you acknowledge that you understand its * function completely and accept all risk in its use. * * @author Ian Kaplan, www.bearcave.com, iank@bearcave.com */ /** * HttpExecute * Oct 23, 2004

Support for sending HTTP POST messages

The HttpExecute class is designed to be used in combination with the Apache "Commons" HttpClient utility class TimeoutController. As the name suggests, the HTTP TimeoutController handles HTTP timeout.

The HttpExecute class is allocated once for each URL. It can be reused for multiple messages to that URL. The setMessage method must be called once for each message, even if the same message is sent multiple times.

Notes:

The Apache documentation does not discuss whether the same PostMethod object can be used in multiple HTTP class. As it turns out, it cannot, although the HttpClient object can be reused. Apparently this is a result of internal variables that have to be reset for each HTTP call. There is a depreciated method, recycle(), which apparently did this in the past. The recycle() method is not only depreciated, it does not seem to properly resent the PostMethod state. So the strange look of the code below, which allocates a new PostMethod for each HTTP call is no accident.

* * @author Ian Kaplan, www.bearcave.com, iank@bearcave.com */ public class HttpExecute implements Runnable { private Exception mException = null; private HttpClient mClient; private PostMethod mPost; private String mURL; private String mReturnMsg = null; /** @param url a URL. For example http://www.bearcave.com or http://localhost:8433 */ public HttpExecute(String url ) { mClient = new HttpClient(); mURL = url; mPost = null; } /** Set the message to be sent to the URL */ public void setMessage( String msg ) { mPost = new PostMethod( mURL ); mPost.setHttp11(false); mPost.setRequestContentLength(PostMethod.CONTENT_LENGTH_AUTO); mPost.setRequestBody( msg ); } /** The "run" method sends the HTTP message. If all goes will it will terminate.

The setMessage() method must be called each time before run() is called, even if the same message is being sent.

*/ public void run() { if (mPost != null) { try { mClient.executeMethod( mPost); mReturnMsg = mPost.getResponseBodyAsString(); mPost.releaseConnection(); mPost = null; } catch (HttpException e) { mException = e; } catch (IOException e) { mException = e; } } else { mException = new Exception("HttpExecute::run: message not set"); } } // run /** */ public String getReturnMsg() { return mReturnMsg; } public Exception getException() { return mException; } } // class HttpExecute