在 Java 中,URL 连接何时关闭? [英] In Java when does a URL connection close?

查看:47
本文介绍了在 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 连接何时关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆