mcfly soft
mcfly soft

Reputation: 11655

URL Connection close hangs sometimes

I have a function that gets the size of a file on a server. I recognize that closing the connection can take a lot of time, like 10 secs or more, sometimes. Now I had the situation, that in the Android emulator it hanged forever, but starting the same app on a real device it went through normally.

Can someone explain this behavior or is there a better way to close the connection?

public static int getFileSizeFromURL(String sUrl) {
    URL url;
    URLConnection conn;
    int size=0;
    try {
      url = new URL(sUrl);
      conn = url.openConnection();
      size = conn.getContentLength();
      if(size < 0){
      } else {
          conn.getInputStream().close(); <----- hangs here in Simulator.
      }
    }
    catch(Exception e) {
      e.printStackTrace();
    }
    return size;
}

Upvotes: 2

Views: 388

Answers (2)

Shubham Bhewanewala
Shubham Bhewanewala

Reputation: 597

When size is zero then connection should be disconnect. and when size is more than zero then connection should get input stream working. Try below code.

public static int getFileSizeFromURL(String sUrl) {
            URL url;
            URLConnection conn;
            int size=0;
            try {
              url = new URL(sUrl);
              conn = url.openConnection();
              size = conn.getContentLength();
              if(size == 0){
                  conn.disconnect();
              }
              else
                  conn.getInputStream(); <----- hangs here in Simulator.
              }
            catch(Exception e) {
              e.printStackTrace();
              }
            return size;
        }

Upvotes: 1

Tobias
Tobias

Reputation: 7771

I think this might be related to your code making a GET request when you should really do a HEAD request:

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");

I am not sure whether this will fix the problem, but the docs say

Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance

and a GET request will definitely use more resources than a HEAD request. Unless a GET request is strictly required, you should avoid it. If you are not sure whether the server supports HEAD requests, try HEAD first and fall back to GET if the first attempt fails.

Upvotes: 0

Related Questions