URLConnection: connection status after closing input stream
843790Jun 20 2006 — edited Jun 21 2006Hi list!
I am using class j.n.URL to acces files in the internet, in the local file system (File.toURL():URL) and in the classpath (ClassLoader.getResource():URL) in a homogenuous way. To read such a file, I have two possibilities:
* create an URLConnection by URL.openConnection()
and then build a connection by connect() and get a stream
by applying getInputStream() on this URLConnection.
* directly call openStream() on the URL object,
which by specification (API of j.n.URL) is equivalent to
'URL.openConnection().getInputStream()'
(seems that 'getInputStream()' connects implicitely?)
Now, my problem is about terminating the opened connection. There seems to be no explicit inverse method to 'URLConnection.connect()' (no 'close()' or something like this). I first thougt that closing the opened input stream would implicitely terminate the connection, too. But I checked the internal status field 'connected' of my URLConnection instance with a debugger, and I saw that it is always 'true' (means 'connection open') after calling 'connect()' once. So does this mean that I have no means to terminate the connection?
It would be an idea to set the connection timeout to 1 (= 1ms) after using the connection (by 'URLConnection.setConnectTimeout(); argument 0 means 'forever'). But I am not sure if this is allowed after a connection is established with 'connect()'. And this trick would only help in the first of the above mentioned cases: In my application I return an open input stream which has to be closed by the caller; the caller does not know anything about URLConnectionS. So in this case I had to return him a special kind of InputStream, which wraps the original InputStream, using delegates to call all its public methods, and which includes a special method 'terminateConnection()' which realizes the above idea.
Any insight in my problem?
Michael Schneider