How to close URL connection?

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? }

  • Answer:

    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.

timdisney at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

Agreed with @kasperjj. By the way, cleanup should really go in a finally{} block...

Eric Wendelin

If you cast to an HttpURLConnection, there is a http://java.sun.com/j2se/1.4.2/docs/api/java/net/HttpURLConnection.html#disconnect() method. If the connection is idle, it will probably disconnect immediately. No guarantees.

James Schek

I've got a strange use-case where I don't open the underlying stream : /** * rewriting for static resources * * @param path the path, with the leading / */ public static String stat(final String path) { try { final URL resource = ServletActionContext.getServletContext().getResource(path); final URLConnection connection = resource.openConnection(); final long l = connection.getLastModified(); return STATIC_CONTENT_PREFIX + path + "?" + l; } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } it's for fooling the browser cache for static resources in my web app (generating urls like: http://static.example.com/static/lol.css?123000000 from an input like "/static/lol.css"). does my code leaks any resources ?

nraynaud

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.