Android getContentLength()为-1 解决方法

  公司的sdk要做一个app下载功能。开始使用的安智的下载链接,程序一直运行正常。但是公司自己的服务器的时候,就报错了。因为要获取文件大小来做进度条,错误位置是在获取文件大小getContentLength()的时候返回-1.对比了一下请求的response,发现就是没有返回文件的ContentLength.  

  网上搜了一下,加入代码

HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn .setRequestProperty("Accept-Encoding", "identity"); 
conn.connect();


发现可以了。

原因:

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压缩。

参考:

http://www.cnblogs.com/helloandroid/archive/2013/01/21/2869776.html

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

原文地址:https://www.cnblogs.com/aosting/p/3436412.html