问题描述
我正在使用HttpURLConnection来下载Java中的页面。我忘了发布连接,我认为这给我的系统造成了一些问题(一个网络浏览器)。
I'm using HttpURLConnection to do download of pages in Java. I forgot to release the connections and I think this was causing some problems to my system (a webcrawler).
现在我做了一些测试,看到断开后,在Windows上的 netstat
命令的结果中,某些连接仍然像TIME_WAIT。
Now I've done some tests and see that after disconnecting, some connections still like TIME_WAIT in the results from the netstat
command on Windows.
如何释放此连接马上?
示例代码:
private HttpURLConnection connection;
boolean openConnection(String url) {
try {
URL urlDownload = new URL(url);
connection = (HttpURLConnection) urlDownload.openConnection();
connection.setInstanceFollowRedirects(true);
connection.connect();
connection.disconnect();
return true;
} catch (Exception e) {
System.out.println(e);
return false;
}
}
推荐答案
In某些实现,如果您已调用 getInputStream
或 getOutputStream
,则需要确保关闭这些流。否则,即使在调用 disconnect
之后连接也可以保持打开状态。
In some implementations, if you have called getInputStream
or getOutputStream
, you need to ensure that those streams are closed. Otherwise, the connection can stay open even after calling disconnect
.
编辑:
这是来自对于HttpURLConnection [强调添加]:
This is from the J2SE docs for HttpURLConnection [emphasis added]:
这是来自:
我不知道知道你正在使用什么平台,但它可能有类似的行为。
I don't know what platform you are using, but it could have similar behavior.
这篇关于在Java中,有多接近连接并使用HttpURLConnection释放端口/套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!