'Properly close of URLConnection using openStream method

I'm getting a little bit confused about how properly close/manage an URLConnection/HttpURLConnection, the next code shows how I'm deal with it:

String someIP = "...";
URL url = new URL(someIP);
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
    while ((res = br.readLine()) != null) {
        cad.append(res);
    }
}

I'm thinking to change the implementation to the next one, using an HttpURLConnection and closing later in finally clause:

String someIP = "...";
URL url = new URL(someIP);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try (InputStreamReader isr = new InputStreamReader(conn.getInputStream());
        BufferedReader br = new BufferedReader(isr)) {
    while ((res = br.readLine()) != null) {
        cad.append(res);
    }
} 
catch (Exception e) {
    //ex....
}
finally {
    if (conn != null) {
        conn.disconnect();
    }
}

It is enough to use a try with resources to properly close the BufferedReader, InputStreamReader and URLConnection? Or the second implementation is better, what advices could you give me to handle it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source