首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文件下载-文件长度为负

文件下载-文件长度为负
EN

Stack Overflow用户
提问于 2015-05-09 23:52:47
回答 1查看 1.1K关注 0票数 6

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

我想要显示下载进度,但我面临着文件大小始终为-1的问题。

截图:

我的代码:

代码语言:javascript
复制
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();
    }

我得到了返回-1 (int fileSize = connection.getContentLength();)的fileSize的垃圾值。

EN

回答 1

Stack Overflow用户

发布于 2015-05-10 05:22:31

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30142026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档