Android - HttpUrlConnection没有关闭.最终导致SocketException

Mar*_*zon 9 java android httpurlconnection

我在运行Jellybean(4.1 - 4.3)的设备中遇到HttpUrlConnection的一些问题,其中连接未关闭并且在执行多次后导致SocketException"Too many open files".

我打算调用HttpUrlConnection.disconnect()并关闭finally块中的所有Inputstream,Outputstream,Reader和Writers.

转到adb shell并执行netstat显示应用程序创建的所有连接都处于CLOSE_WAIT状态.

InputStream inputStream = httpUrlConnection.getInputStream();

// After calling inputStream.read() then the problem occurs. I think the 
// inputstream doesn't get closed even after calling close in a finally block. 
// The InputStream is a ChunkedInputStream if that helps.
Run Code Online (Sandbox Code Playgroud)

我尝试过在2.3.3,4.0.3和4.4上运行的其他设备并没有遇到这个问题.

还有其他方法可以手动关闭连接吗?

Mar*_*zon 12

我终于找到了解决方法.似乎Jellybean在"Keep-Alive"连接上存在问题.我刚刚将Connection = Close添加到我的请求标题中,现在一切正常.做一个netstat,我看到连接现在正在关闭,由于"打开的文件太多",我不再收到SocketException.

  • @TimT`connection.setRequestProperty("Connection","Close");` (6认同)