简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM