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
getInputStreamorgetOutputStream, you need to ensure that those streams are closed. Otherwise, the connection can stay open even after callingdisconnect.EDIT:
This is from the J2SE docs for HttpURLConnection [emphasis added]:
And this is from the Android docs:
I don’t know what platform you are using, but it could have similar behavior.