在Java中什么时候URL连接关闭? [英] In Java when does a URL connection close?

查看:1136
本文介绍了在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?
}


推荐答案

在协议中规定。有些维护持久连接,其他关闭它们的连接,当您的呼叫关闭在输入或输出流由连接给定。

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


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

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天全站免登陆