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

巧了我就是萌 提交于 2019-11-29 12:08:45

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.

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