在Java中,有多接近连接并使用HttpURLConnection释放端口/套接字? [英] In Java, how close the connection and free the port/socket using HttpURLConnection?

查看:980
本文介绍了在Java中,有多接近连接并使用HttpURLConnection释放端口/套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

编辑:

这是来自 J2SE docs 对于HttpURLConnection [强调添加]:

This is from the J2SE docs for HttpURLConnection [emphasis added]:


调用disconnect()方法可能关闭底层socket,如果持久连接在那个时候是空闲的。

Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.

这是来自 Android文档


为了减少延迟,该类可以为多个请求/响应对重用相同的底层Socket。因此,HTTP连接可能会保持打开的时间超过必要的时间。调用disconnect()将套接字返回到已连接套接字池。在发出任何HTTP请求之前,可以通过将http.keepAlive系统属性设置为false来禁用此行为。 http.maxConnections属性可用于控制每个服务器的空闲连接数。

To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs. As a result, HTTP connections may be held open longer than necessary. Calls to disconnect() return the socket to a pool of connected sockets. This behavior can be disabled by setting the "http.keepAlive" system property to "false" before issuing any HTTP requests. The "http.maxConnections" property may be used to control how many idle connections to each server will be held.

我不知道知道你正在使用什么平台,但它可能有类似的行为。

I don't know what platform you are using, but it could have similar behavior.

这篇关于在Java中,有多接近连接并使用HttpURLConnection释放端口/套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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