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

我想显示下载进度,但是我遇到了一个问题,即文件大小始终为-1

屏幕截图:

我的代码:

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的垃圾值,该值返回-1(int fileSize = connection.getContentLength();)

最佳答案

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

关于java - 文件下载-负文件长度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30142026/

10-10 14:02
查看更多