When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?
i.e. is this safe?
HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL().openConnection(); conn.connect(); // check for content type I don't care about if (conn.getContentType.equals("image/gif") return; // get stream and read from it InputStream is = conn.getInputStream(); try { // read from is } finally { is.close(); }
Secondly, is it safe to close an InputStream before all of it's content has been fully read?
Is there a risk of leaving the underlying socket in ESTABLISHED or even CLOSE_WAIT state?
it's not thread safe. you shouldn't cache/share a connection. just create a new connection for each request. there is certainly a little overhead in creating new connections, but it is very small, you shouldn't worry about it.
Yes you need to close the inputstream first and close httpconnection next. As per javadoc.
The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. It sets whether HTTP redirects (requests with response code) should be automatically followed by HttpURLConnection class.
You don't. You close this one and create a new one.
According to http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html and OpenJDK source code.
(When keepAlive == true
)
If client called HttpURLConnection.getInputSteam().close()
, the later call to HttpURLConnection.disconnect()
will NOT close the Socket
. i.e. The Socket
is reused (cached)
If client does not call close()
, call disconnect()
will close the InputStream
and close the Socket
.
So in order to reuse the Socket
, just call InputStream.close()
. Do not call HttpURLConnection.disconnect()
.
is it safe to close an InputStream before all of it's content has been read
You need to read all of the data in the input stream before you close it so that the underlying TCP connection gets cached. I have read that it should not be required in latest Java, but it was always mandated to read the whole response for connection re-use.
Check this post: keep-alive in java6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With