Skip to content Skip to sidebar Skip to footer

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 op

Solution 1:

I finally found a workaround. It seems that Jellybean is having an issue on "Keep-Alive" connections. I just added Connection=Close to my request header and now all is working. 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".

Solution 2:

Check If you have tried all of the below... There might be something missing.. other wise it should not have any problem.

InputStream in;
HttpsURLConnectionurlConnection=null;
try {
    URLurl=newURL(Url);

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

    in = urlConnection.getInputStream();
    intresponseCode= urlConnection.getResponseCode();

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

Solution 3:

You might be better off not calling disconnect() and thus allowing it to do HTTP connection pooling.

Solution 4:

Try using OkHttp Instead.

Once you get the Maven dependency added, you can do something like the following to download a file:

OkHttpClientokHttpClient=newOkHttpClient.Builder().build();

OutputStreamoutput=null;

try {
  Requestrequest=newRequest.Builder().url( download_url ).build();
  Responseresponse= okHttpClient.newCall( request ).execute();

  if ( !response.isSuccessful() ) {
    thrownewFileNotFoundException();
  }

  output = newFileOutputStream( output_path );

  output.write( response.body().bytes() );
}
finally {
  // Ensure streams are closed, even if there's an exception.if ( output != null ) output.flush();
  if ( output != null ) output.close();
}

Switching to OkHttp instantly fixed our leaked file descriptor issue so it's worth trying if you're stuck, even at the expense of adding another library dependency.

Post a Comment for "Android - Httpurlconnection Is Not Closing. Eventually Results To Socketexception"