您的位置:首页 > 理论基础 > 计算机网络

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

2014-08-20 19:57 405 查看
做一个andriod系统,测试的时候是在android 2.2系统上测试的一切正常,等发布的时候发现个小问题,就是当程序有更新时,需要重新下载APK,为了友好,做了个进度条,但是在 2.2以上的系统中进度条不会走动,部分代码如下:
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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: