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

      接手一个项目出现一个问题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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android下载文件可以使用以下步骤: 1. 添加网络权限:在 AndroidManifest.xml 文件中添加以下权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 2. 创建一个异步任务(AsyncTask)或者使用线程(Thread)来执行下载操作。以下是使用异步任务的示例: ```java public class DownloadTask extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... urls) { String fileUrl = urls[0]; String fileName = urls[1]; try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); int fileLength = connection.getContentLength(); InputStream inputStream = connection.getInputStream(); FileOutputStream outputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName); byte[] buffer = new byte[1024]; int bytesRead; long totalBytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { totalBytesRead += bytesRead; outputStream.write(buffer, 0, bytesRead); // 发布进度更新 publishProgress((int) (totalBytesRead * 100 / fileLength)); } outputStream.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } return fileName; } @Override protected void onProgressUpdate(Integer... progress) { // 进度更新 int percentage = progress[0]; // 可以在这里更新UI组件,例如进度条 } @Override protected void onPostExecute(String fileName) { // 下载完成 // 可以在这里执行一些完成后的操作,例如显示通知或者打开文件 } } ``` 3. 在需要下载文件的地方,创建一个 DownloadTask 对象并执行它: ```java String fileUrl = "http://example.com/file.pdf"; String fileName = "file.pdf"; DownloadTask downloadTask = new DownloadTask(); downloadTask.execute(fileUrl, fileName); ``` 以上代码会将文件从指定的 URL 下载到设备的存储目录中。你可以根据需要修改文件的保存路径和名称。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值