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