Safe use of HttpURLConnection(安全使用 HttpURLConnection)
问题描述
在使用 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?
推荐答案
关闭 InputStream 是否安全在它的所有内容被阅读
is it safe to close an InputStream before all of it's content has been read
您需要在关闭输入流之前读取输入流中的所有数据,以便缓存底层 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.
查看这篇文章:keep-alive injava6
这篇关于安全使用 HttpURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:安全使用 HttpURLConnection
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01