In Java when does a URL connection close?(在 Java 中,URL 连接何时关闭?)
问题描述
java 什么时候放弃与 URL 的连接?我在 URL 或 URLConnection 上都没有看到 close() 方法,所以它会在请求完成后立即释放连接吗?我主要是想看看我是否需要在异常处理程序中进行任何清理.
When does java let go of a connections to a URL? I don't see a close() method on either URL or URLConnection so does it free up the connection as soon as the request finishes? I'm mainly asking to see if I need to do any clean up in an exception handler.
try {
URL url = new URL("http://foo.bar");
URLConnection conn = url.openConnection();
// use the connection
}
catch (Exception e) {
// any clean up here?
}
推荐答案
这取决于协议中指定的具体协议.一些保持持久连接,另一些在连接给定的输入或输出流中关闭呼叫时关闭它们的连接.但除了记住关闭从 URLConnection 打开的流之外,您无能为力.
It depends on the specific protocol specified in the protocol. Some maintain persistent connections, other close their connections when your call close in the input or outputstream given by the connection. But other than remembering to closing the streams you opened from the URLConnection, there is nothing else you can do.
来自 java.net.URLConnection 的 javadoc
From the javadoc for java.net.URLConnection
调用 close() 方法输入流或输出流请求后的 URLConnection 可能会释放与此相关的网络资源实例,除非特定协议规格指定不同行为.
Invoking the close() methods on the InputStream or OutputStream of an URLConnection after a request may free network resources associated with this instance, unless particular protocol specifications specify different behaviours for it.
这篇关于在 Java 中,URL 连接何时关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中,URL 连接何时关闭?


基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01