Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java when does a URL connection close?

When does java let go of a connections to a URL? I don't see a close() method on either URL or URLConnection so does it free up the connection as soon as the request finishes? I'm mainly asking to see if I need to do any clean up in an exception handler.

try {   URL url = new URL("http://foo.bar");   URLConnection conn = url.openConnection();   // use the connection } catch (Exception e) {   // any clean up here? } 
like image 756
timdisney Avatar asked Nov 07 '08 17:11

timdisney


People also ask

How do I close a URL connection?

To close the connection, invoke the close() method on either the InputStream or OutputStream object. Doing that may free the network resources associated with the URLConnection instance.

What is URL connection in java?

The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL.

Do I need to disconnect HttpURLConnection?

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

What is the date URL connection class return?

HttpURLConnection class is the class in java which deals with all the operations related to URL connection. getDate() method of HttpURLConnection class is the method that is used to get the date and time of the URL Connection.


2 Answers

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.

like image 35
kasperjj Avatar answered Sep 20 '22 05:09

kasperjj


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

like image 123
James Schek Avatar answered Sep 20 '22 05:09

James Schek