0

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ファイルサイズはブラウザで簡単に計算できます。

解決策を教えてください。

4

2 に答える 2

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

この回答に基づくコード

于 2016-06-29T11:56:48.740 に答える