2012-02-05 60 views
32

我见过很多不同的使用HttpURLConnection + InputStream的例子,并在使用后关闭它们(或者不关闭它们)。这是我想出的,以确保完成后所有内容都关闭,无论是否存在错误。这是有效的?:正确关闭URLConnection和InputStream?

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(); 
    } 
} 

感谢

回答

18

是的。在做最后的端部将是最好的主意,因为如果代码某处出现故障时,程序将无法达到,直到.close().disconnect()声明,我们保持之前catch语句...

如果代码某处出现故障和异常被抛出在节目之间,还是终于得到无论抛出异常的执行...

+5

你也想setConnectTimeout和setReadTimeout等等如果服务器不可用或有读取错误,则连接不会永久锁定。 – 2012-02-05 15:18:01

+1

@metalideath - 当然,为了简明起见,我省略了它们,如果有人使用它作为复制/粘贴,将在示例中添加一个注释。 – user291701 2012-02-05 15:21:14

+0

@metalideath:与你同意...在这里我只是按照每个问题的答案...这个世界上有很多事情,我们必须去探索它... – 2012-02-05 15:25:29