URL 连接关闭有时挂起

URL Connection close hangs sometimes

我有一个函数可以获取服务器上文件的大小。我认识到关闭连接可能会花费很多时间,有时需要 10 秒或更长时间。 现在我遇到了这种情况,在 Android 模拟器中它永远挂起,但在真实设备上启动同一个应用程序它正常通过。

有人可以解释这种行为吗?或者有更好的方法来关闭连接吗?

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;
}

我认为这可能与您的代码发出 GET 请求有关,而您实际上应该发出 HEAD 请求:

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

我不确定这是否能解决问题,但文档说

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

GET 请求肯定会比 HEAD 请求使用更多的资源。除非严格要求 GET 请求,否则您应该避免它。如果您不确定服务器是否支持 HEAD 请求,请先尝试 HEAD,如果第一次尝试失败则回退到 GET

当大小为零时,应该断开连接。当大小大于零时,连接应该使输入流工作。试试下面的代码。

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;
        }