简体   繁体   English

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

[英]Android - HttpUrlConnection is not closing. Eventually results to SocketException

I am encountering some problems with the HttpUrlConnection in devices running Jellybean (4.1 - 4.3) wherein connections are not closed and results to a SocketException "Too many open files" after executing a number of times. 我在运行Jellybean(4.1 - 4.3)的设备中遇到HttpUrlConnection的一些问题,其中连接未关闭并且在执行多次后导致SocketException“Too many open files”。

I do call HttpUrlConnection.disconnect() and am closing all the Inputstream, Outputstream, Reader and Writers in a finally block. 我打算调用HttpUrlConnection.disconnect()并关闭finally块中的所有Inputstream,Outputstream,Reader和Writers。

Going to adb shell and executing a netstat shows all the connections created by the application are left in CLOSE_WAIT state. 转到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.

I have tried other devices running on 2.3.3, 4.0.3 and 4.4 and did not encounter this issue. 我尝试过在2.3.3,4.0.3和4.4上运行的其他设备并没有遇到这个问题。

Is there another way that I can manually close the connections? 还有其他方法可以手动关闭连接吗?

I finally found a workaround. 我终于找到了解决方法。 It seems that Jellybean is having an issue on "Keep-Alive" connections. 似乎Jellybean在“Keep-Alive”连接上存在问题。 I just added Connection=Close to my request header and now all is working. 我刚刚将Connection = Close添加到我的请求标题中,现在一切正常。 Doing a netstat, I see that the connections are now being closed and I no longer get the SocketException due to "Too many open files". 做一个netstat,我看到连接现在正在关闭,由于“打开的文件太多”,我不再收到SocketException。

Check If you have tried all of the below... There might be something missing.. other wise it should not have any problem. 检查如果你已经尝试了以下所有...可能有一些东西丢失..其他明智的应该没有任何问题。

InputStream in;
HttpsURLConnection urlConnection =null;
try {
    URL url = new URL(Url);

    urlConnection = (HttpsURLConnection) url
                     .openConnection();
    //5 Second timeout
    urlConnection.setReadTimeout(5*1000);

    in = urlConnection.getInputStream();
    int responseCode = urlConnection.getResponseCode();

    if (responseCode != HttpURLConnection.HTTP_OK) {
         InputStream errInputStream = urlConnection.getErrorStream();
        //Print error message and response code..
         errInputStream.close();
    }
    in.close();
} catch (Exception e) {
    e.printStackTrace();
} finally{
    if(urlConnection != null)
        urlConnection.disconnect();
}

你可能最好不要调用disconnect() ,从而允许它进行HTTP连接池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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