Friday, March 4, 2011

Apache Commons HTTPClient 3.x leaving connections open

I'm using HttpClient to execute a PostMethod against a remote servlet and for some reason a lot of my connections are hanging open and hogging up all of my server's connections.
Here's more info about the architecture
GWT client calls into a GWT Service
GWT service instantiates a HttpClient, creates a PostMethod and has the client execute the method
it then gets the input stream by calling method.getResponseBodyAsStream() and writes it out to a byte array
it then closes the input stream and flushes the byte array output stream, does a few more lines of code and then calls method.releaseConnection()

There has to be something obvious I'm overlooking that's causing this. If I perform a GET in a browser to the same service, the connections close immediately but something about HTTPClient is causing them to hang open.

From stackoverflow
  • You need to call HttpMethodBase#releaseConnection(). If you return a InputStream to be used later, a simple way is to wrap it by a anonymous FilterInputStream overwriting close():

    final HttpMethodBase method = ...;
    return new FilterInputStream(method.getResponseBodyAsStream())
    {
      public void close() throws IOException
      {
        try {
          super.close();
        } finally {
          method.releaseConnection();
        }
      }
    };
    

0 comments:

Post a Comment