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();
}
}
感谢
你也想setConnectTimeout和setReadTimeout等等如果服务器不可用或有读取错误,则连接不会永久锁定。 – 2012-02-05 15:18:01
@metalideath - 当然,为了简明起见,我省略了它们,如果有人使用它作为复制/粘贴,将在示例中添加一个注释。 – user291701 2012-02-05 15:21:14
@metalideath:与你同意...在这里我只是按照每个问题的答案...这个世界上有很多事情,我们必须去探索它... – 2012-02-05 15:25:29