http urlconnection getcontentlength总返回值为-1

来源:互联网 发布:细菌 线粒体 知乎 编辑:程序博客网 时间:2024/05/16 08:15

最近在做一个自动更新的功能,点击更新下载之后,进度条不走动。之前一直用的模拟器运行,没有发现任何问题,后来真机测试时就出现了进度条不走动的问题。经断点调试发现,当获取下载文件大小getContentLength()的时候,返回结果是-1。于是上网搜了一下HttpURLConnection及getContentLength(),发现2.2版本以上HttpURLConnection跟服务交互采用了”gzip”压缩:参考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: whenread() returns -1.

解决办法:在http request的head中设置如下参数即可:conn.setRequestProperty(“Accept-Encoding”, “identity”);

0 0