sroj
sroj

Reputation: 254

Need to call java.net.HttpURLConnection.disconnect() after using connection?

I'm using java.net.HttpURLConnection on Android (API 16). I use connect() and then getInputStream() to obtain an InputStream to read data from the connection. After I use the InputStream (i.e. consume the data), I close() it.

The question is: does this also closes the underlying HttpURLConnection (as if by calling disconnect() on it)? My guess is not, but I just want to confirm this. The more general question is: Do I need to call java.net.HttpURLConnection.disconnect() when the connection is no longer useful?

The thing is that I have a method to open a HttpURLConnection to a given host. The signature is: InputStream OpenHttpConnection(String stringURL, String method). That returns an InputStream, which the caller uses to read data from the connection, but if I call disconnect() from within the body of that method, then the InputStream is closed and becomes useless (I have confirmed this). But if, on the other hand, the connection isn't closed when I call close() on the InputStream, from the caller, then I will have a connection wasting resources.

Any suggestions?

Upvotes: 1

Views: 3352

Answers (1)

devunwired
devunwired

Reputation: 63293

Calling disconnect() does close the underlying streams if they are still open, but it additionally releases the connection's resources back to the connection pool, so it is still a good idea to call it when you are able (and finished with the connection) even if you are closing the streams discretely elsewhere.

Upvotes: 7

Related Questions