Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe use of HttpURLConnection

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?

like image 247
Joel Avatar asked Jan 22 '11 11:01

Joel


People also ask

Is HttpURLConnection thread safe?

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.

Do we need to disconnect HttpURLConnection?

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

When should I use HttpURLConnection?

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.

Can I reuse HttpURLConnection?

You don't. You close this one and create a new one.


2 Answers

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().

like image 75
Anderson Mao Avatar answered Sep 20 '22 00:09

Anderson Mao


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

like image 21
Cratylus Avatar answered Sep 20 '22 00:09

Cratylus