在 Java 中,URL 连接何时关闭?

2022-01-24 00:00:00 connection exception url java

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.

相关文章