Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing URLConnection and InputStream correctly?

Tags:

java

I've seen many different examples of using HttpURLConnection + InputStream, and closing them (or not closing them) after use. This is what I came up with to make sure everything is closed after finished, whether there's an error or not. Is this valid?:

HttpURLConnection conn = null; InputStream is = null; try {     URL url = new URL("http://example.com");      // (set connection and read timeouts on the connection)     conn = (HttpURLConnection)url.openConnection();      is = new BufferedInputStream(conn.getInputStream());      doSomethingWithInputStream(is);  } catch (Exception ex) { } finally {     if (is != null) {         try {             is.close();         } catch (IOException e) {         }     }     if (conn != null) {         conn.disconnect();     } } 

Thanks

like image 506
user291701 Avatar asked Feb 05 '12 14:02

user291701


People also ask

How do I close URLConnection?

To close the connection, invoke the close() method on either the InputStream or OutputStream object. Doing that may free the network resources associated with the URLConnection instance.

What is the purpose of URLConnection class?

The Java URLConnection class represents a communication link between the URL and the application. It can be used to read and write data to the specified resource referred by the URL.

What is URLConnection in Java?

The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL.


1 Answers

Yep.. Doing the end part in finally would be best idea because if code fails somewhere, program won't reach till .close(), .disconnect() statements that we keep before catch statements...

If the code fails somewhere and exception is thrown in between of the program, still finally get executed regardless of exception thrown...

like image 137
Fahim Parkar Avatar answered Sep 18 '22 21:09

Fahim Parkar