zoukankan      html  css  js  c++  java
  • 获取网络文件长度问题

       当下载某些文件需要显示进度的时候,就需要先获取将下载文件总长度.再根据下载的完成度与总长度显示进度条.获取文件长度的方法如下:

       HttpURLConnection conn = (HttpURLConnection)url.openConnection();    conn.connect();

       int length = conn.getContentLength();

       那么问题来了,lenght的值为-1.在网上查资料都说是服务端没有设content length,跟服务端协商,加上这个就行了.查API :Returns the content length in bytes specified by the response header field content-length or -1 if this field is not set.看API也似乎是这个意思。本来打算投降了,跟服务端商量下,看能不能主动加上.突然手贱多点了下查找,发现这么一段话:

          By default this implementation of HttpURLConnection requests that servers use gzip compression. Since getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getInputStream(). Instead, read that stream until it is exhausted: when read() returns -1. Gzip compression can be disabled by setting the acceptable encodings in the request header。

    似乎是说,在默认情况下,HttpURLConnection 使用 gzip方式获取,文件 getContentLength() 这个方法,每次read完成后可以获得,当前已经传送了多少数据,而不能用这个方法获取 需要传送多少字节的内容,当read() 返回 -1时,读取完成,由于这个压缩后的总长度我无法获取,那么进度条就没法计算值了。

    要取得长度则,要求http请求不要gzip压缩,具体设置如下

    HttpURLConnection conn = (HttpURLConnection)url.openConnection();

    conn .setRequestProperty("Accept-Encoding", "identity"); 

    conn.connect();

    int length = conn.getContentLength();

  • 相关阅读:
    多线程 分配
    fopen:文本和二进制方式打开方式对比【转】
    C优先级列表【转】
    sscanf用法
    heap和stack【转】
    大端小端【转】
    二级指针与二维数组的秘密【二者不等】
    C++中的空类编译器默认隐式声明哪些成员函数【CSDN】
    项目内存泄漏问题及解决方案后续
    浅谈部门前台框架中的几个方法<一>
  • 原文地址:https://www.cnblogs.com/lianghe01/p/4367829.html
Copyright © 2011-2022 走看看