Android - HttpUrlConnection is not closing. Eventually results to SocketException

前端 未结 4 1211
我在风中等你
我在风中等你 2020-12-15 11:03

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

相关标签:
4条回答
  • Try using OkHttp Instead.

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

    OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    
    OutputStream output = null;
    
    try {
      Request request   = new Request.Builder().url( download_url ).build();
      Response response = okHttpClient.newCall( request ).execute();
    
      if ( !response.isSuccessful() ) {
        throw new FileNotFoundException();
      }
    
      output = new FileOutputStream( 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.

    0 讨论(0)
  • 2020-12-15 11:39

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

    0 讨论(0)
  • 2020-12-15 11:41

    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".

    0 讨论(0)
  • 2020-12-15 11:42

    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();
    }
    
    0 讨论(0)
提交回复
热议问题