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

来源:互联网 发布:exsi虚拟机linux网络 编辑:程序博客网 时间:2024/06/05 23:06

转载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
原创粉丝点击