作一个andriod系统,测试的时候是在android 2.2系统上测试的一切正常,等发布的时候发现个小问题,就是当程序有更新时,须要从新下载APK,为了友好,作了个进度条,可是在 2.2以上的系统中进度条不会走动,部分代码以下: android
HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.connect(); ide
int length = conn.getContentLength(); 测试
InputStream is = conn.getInputStream(); this
通过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也彷佛是这个意思。原本打算投降了,跟服务端商量下,看能不能主动加上。忽然手贱多点了下查找,发现这么一段话: url
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。 spa
彷佛是说,在默认状况下,HttpURLConnection 使用 gzip方式获取,文件 getContentLength() 这个方法,每次read完成后能够得到,当前已经传送了多少数据,而不能用这个方法获取 须要传送多少字节的内容,当read() 返回 -1时,读取完成,因为这个压缩后的总长度我没法获取,那么进度条就无法计算值了。 debug
要取得长度则,要求http请求不要gzip压缩,具体设置以下 code
HttpURLConnection conn = (HttpURLConnection)url.openConnection(); server
conn .setRequestProperty("Accept-Encoding", "identity");conn.connect();int length = conn.getContentLength(); ip
InputStream is = conn.getInputStream();