Safe use of HttpURLConnection

2022-08-31 16:07:15

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?


答案 1

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 , the later call to will NOT close the . i.e. The is reused (cached)HttpURLConnection.getInputSteam().close()HttpURLConnection.disconnect()SocketSocket

If client does not call , call will close the and close the .close()disconnect()InputStreamSocket

So in order to reuse the , just call . Do not call .SocketInputStream.close()HttpURLConnection.disconnect()


答案 2

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