下载网络文件HttpURLConnection.getContentLength()大小为 -1

转载http://my.oschina.net/u/133352/blog/96582

请求下载一个网页时,进度条一直不走动

部分让你代码如下:

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

 int length = conn.getContentLength();

   InputStream is = conn.getInputStream();

经过debug,发现是由于,conn.getContentLength() 时获取到的值为 -1,导致计算进度时,结果有误,永远为负数。在网上查资料都说是服务端没有设content length,跟服务端协商,加上这个就行了。但是为毛2.2,的时候就可以服务端也没设啊,查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();

InputStream is = conn.getInputStream();


               

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值