In Java, how close the connection and free the port/socket using HttpURLConnection?

孤人 提交于 2019-11-28 05:11:18

问题


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).

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.

How I do to free this connection immediately?

Example code:

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;
    }
}

回答1:


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.

EDIT:

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

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

And this is from the Android docs:

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.




回答2:


The TME_WAIT state is imposed by TCP, not by Java. It lasts two minutes. This is normal.



来源:https://stackoverflow.com/questions/6165752/in-java-how-close-the-connection-and-free-the-port-socket-using-httpurlconnecti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!