In Java when does a URL connection close?

If you cast to an HttpURLConnection, there is a disconnect() method. If the connection is idle, it will probably disconnect immediately. No guarantees.


It depends on the specific protocol specified in the protocol. Some maintain persistent connections, other close their connections when your call close in the input or outputstream given by the connection. But other than remembering to closing the streams you opened from the URLConnection, there is nothing else you can do.

From the javadoc for java.net.URLConnection

Invoking the close() methods on the InputStream or OutputStream of an URLConnection after a request may free network resources associated with this instance, unless particular protocol specifications specify different behaviours for it.