问题描述
当使用HttpURLConnection时,如果我们不获取并使用它,则需要关闭InputStream吗?
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?
即。这是安全吗?
HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL().openConnection();
conn.connect();
// check for content type I don't care about
if (conn.getContentType.equals("image/gif") return;
// get stream and read from it
InputStream is = conn.getInputStream();
try {
// read from is
} finally {
is.close();
}
其次,在所有内容完全关闭之前关闭InputStream 是否安全阅读 ?
Secondly, is it safe to close an InputStream before all of it's content has been fully read?
是否存在将底层套接字置于ESTABLISHED或甚至CLOSE_WAIT状态的风险?
Is there a risk of leaving the underlying socket in ESTABLISHED or even CLOSE_WAIT state?
推荐答案
您需要在关闭之前读取输入流中的所有数据,以便底层TCP连接被缓存。我已经读过它应该在最新的Java中不是必需的,但它总是被要求读取连接重用的整个响应。
You need to read all of the data in the input stream before you close it so that the underlying TCP connection gets cached. I have read that it should not be required in latest Java, but it was always mandated to read the whole response for connection re-use.
查看此帖子:
这篇关于安全使用HttpURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!