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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/272910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:21:18  来源:igfitidea点击:

In Java when does a URL connection close?

javaexceptionurlconnection

提问by timdisney

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.

java 什么时候放弃与 URL 的连接?我在 URL 或 URLConnection 上都没有看到 close() 方法,所以它会在请求完成后立即释放连接吗?我主要是问我是否需要在异常处理程序中进行任何清理。

try {
  URL url = new URL("http://foo.bar");
  URLConnection conn = url.openConnection();
  // use the connection
}
catch (Exception e) {
  // any clean up here?
}

采纳答案by kasperjj

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.

这取决于协议中指定的特定协议。一些维护持久连接,另一些在您的调用在连接给出的输入或输出流中关闭时关闭它们的连接。但除了记住关闭从 URLConnection 打开的流之外,您无能为力。

From the javadoc for java.net.URLConnection

来自 java.net.URLConnection 的 javadoc

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.

在请求之后调用 URLConnection 的 InputStream 或 OutputStream 上的 close() 方法可能会释放与此实例关联的网络资源,除非特定的协议规范为其指定了不同的行为。

回答by James Schek

If you cast to an HttpURLConnection, there is a disconnect()method. If the connection is idle, it will probably disconnect immediately. No guarantees.

如果您转换为 HttpURLConnection,则有一个disconnect()方法。如果连接空闲,它可能会立即断开连接。没有保证。