Skip to content Skip to sidebar Skip to footer

Do I Need To Call Httpurlconnection.disconnect After Finish Using It

The following code basically works as expected. However, to be paranoid, I was wondering, to avoid resource leakage, Do I need to call HttpURLConnection.disconnect, after finish i

Solution 1:

Yes you need to close the inputstream first and close httpconnection next. As per javadoc.

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.

Next two questions answer depends on purpose of your connection. Read this link for more details.

Solution 2:

I believe the requirement for calling setDoInput() or setDoOutput() is to make sure they are called before anything is written to or read from a stream on the connection. Beyond that, I'm not sure it matters when those methods are called.

Post a Comment for "Do I Need To Call Httpurlconnection.disconnect After Finish Using It"