Android2.2以上版本下载网络文件getContentLength()大小异常

来源:互联网 发布:mac版photoshop快捷键 编辑:程序博客网 时间:2024/06/06 09:27

Android2.2以上版本下载网络文件getContentLength()大小异常

 (2012-07-31 14:28:17)
转载
标签: 

it

 分类: Android
      接手一个项目出现一个问题2.2以上的版本下载网络资源不完整无法更新。check代码后发现通过HttpURLConnection.getContentLength()获取的size跟下载下来的file的legth不等。奇怪的是下载3个文件前2个都pass最后一个下载的文件的长度比 HttpURLConnection.getContentLength()获取的size小。自己搭建了个tomcat服务器就正常了。为什么.net服务器就不行。这么诡异的问题恐怕只能请apache组织来解决了。
      不过经过小弟对
 HttpURLConnection的源码的挖掘,发现了HttpURLConnection跟服务交互采用了"gzip"压缩。所以下载的fileLegth > HttpURLConnection.getContentLength().参考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. 
     api上也不推荐是用该方法来验证文件的完整性。可目前项目有不能修改服务器。通过继续研究api发现这种gzip压缩方式是可以取消的。取消办法这http request的head中设置如下参数即可:
     urlConnection.setRequestProperty("Accept-Encoding", "identity"); 
    至此基本上面诡异的问题修复。2.2以上的版本默认都是采用压缩优化希望大家注意。关于文件的完整性验证希望大家还是走md5吧。

阅读全文
0 0