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

问题描述 投票:9回答:4

我在运行Jellybean(4.1-4.3)的设备中的HttpUrlConnection遇到一些问题,其中连接未关闭,并且执行多次后导致SocketException“打开的文件过多”。

我确实调用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.

我尝试了在2.3.3、4.0.3和4.4上运行的其他设备,但没有遇到此问题。

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

java android httpurlconnection
4个回答
12
投票

我终于找到了解决方法。似乎软糖在“保持活动”连接上有问题。我刚刚将Connection = Close添加到我的请求标头中,现在一切正常。在执行netstat时,我看到连接现在正在关闭,并且由于“打开的文件太多”,我不再得到SocketException。


1
投票

检查您是否尝试过以下所有方法...可能缺少一些东西。否则,它应该没有任何问题。


0
投票

您可能会更好[调用disconnect(),从而允许它进行HTTP连接池。


0
投票
尝试使用OkHttp代替。
© www.soinside.com 2019 - 2024. All rights reserved.