【问题标题】:Android getContentLength return -1 but in browser returns the file size , how?Android getContentLength 返回 -1 但在浏览器中返回文件大小,如何?
【发布时间】:2016-06-07 21:22:38
【问题描述】:

我正在尝试使用 Android 从 URL 中查找文件大小,但我得到 getContentLength() : -1,但如果我将在任何浏览器中打开 url,则浏览器可以计算文件大小,其中作为浏览器也是一个客户端应用程序。

我的代码:

 try {
        URL url = new URL("https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=0");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return "Server returned HTTP " + connection.getResponseCode()
                    + " " + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        //fileLength  : -1;  

    } catch (Exception e) {
        return e.toString();
    } finally {
        try {
            if (output != null)
                output.close();
            if (input != null)
                input.close();
        } catch (IOException ignored) {
        }

        if (connection != null)
            connection.disconnect();
    }

这是我上面的android代码,我得到-1作为文件长度,但相同的URL文件大小可以很容易地被浏览器计算出来。

请给我一些解决方案。

【问题讨论】:

    标签: android url browser download http-content-length


    【解决方案1】:

    这段代码对我来说很好用:

    public int getFileSizeFromURL(String urlPath) {
        int fileSize = 0;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection connection = (HttpURLConnection)     url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            fileSize = connection.getContentLength();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileSize;
    }
    

    代码基于this answer

    【讨论】:

      【解决方案2】:

      尝试更改链接

      "https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=0" 
      

      "https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=1"
      

      【讨论】:

        猜你喜欢
        • 2014-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-17
        • 1970-01-01
        • 2015-07-18
        • 2018-06-06
        相关资源
        最近更新 更多