文件下载 - 负文件长度

时间:2015-05-09 15:52:47

标签: java android

我正在尝试从我的服务器下载文件(mp3)。

我想显示下载进度,但我遇到的问题是整个文件大小为-1

截图: enter image description here
我的代码:

try {
    URL url = new URL(urls[0]);
    // URLConnection connection = url.openConnection();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();
    int fileSize = connection.getContentLength();
    if (fileSize == -1)
        fileSize = connection.getHeaderFieldInt("Length", -1);
    InputStream is = new BufferedInputStream(url.openStream());
    OutputStream os = new FileOutputStream(myFile);

    byte data[] = new byte[1024];
    long total = 0;
    int count;
    while ((count = is.read(data)) != -1) {
        total += count;
        Log.d("fileSize", "Lenght of file: " + fileSize);
        Log.d("total", "Lenght of file: " + total);
        // publishProgress((int) (total * 100 / fileSize));
        publishProgress("" + (int) ((total * 100) / fileSize));
        os.write(data, 0, count);
    }
    os.flush();
    os.close();
    is.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

我获得fileSize的垃圾值,返回-1int fileSize = connection.getContentLength();

1 个答案:

答案 0 :(得分:2)

检查服务器正在发送的标头。服务器很可能正在发送Transfer-Encoding: Chunked而没有Content-Length标头。这是HTTP / 1.1中的常见做法。如果服务器没有发送长度,客户端显然无法知道。如果是这种情况,并且您无法控制服务器代码,那么最好的办法可能只显示一个微调器类型的指示器。