Android getContentLength在下载apk文件时始终返回-1 [英] Android getContentLength always return -1 when downloading apk file

查看:210
本文介绍了Android getContentLength在下载apk文件时始终返回-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在我的Android项目中下载文件:

I'm using the following code for downloading file in my Android project:

URL url = new URL(fileUrl);
URLConnection conection= url.openConnection();
conection.setDoOutput(true);
conection.connect();
int lenghtOfFile = conection.getContentLength();

如果 fileUrl 是apk,则 lenghtOfFile 始终返回-1.
但是,如果它是图像,视频类型,则... longengtOfFile返回正好.

If fileUrl is apk, lenghtOfFile always return -1.
But if it is image, video type,... lenghtOfFile return is exactly.

为什么?

我正在使用eclipse,Android SDK版本23.

推荐答案

内容长度并非始终可用,因为默认情况下Android请求GZIP压缩响应.来源: Android文档.

The content length is not always available because by default Android request a GZIP compressed response. Source: Android documentation.

引用链接:

默认情况下,此HttpURLConnection的实现要求 服务器使用gzip压缩,并自动解压缩 getInputStream()的调用者的数据. Content-Encoding和 在这种情况下,将清除Content-Length响应头.压缩文件 可以通过在 请求标头:

By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream(). The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can be disabled by setting the acceptable encodings in the request header:

urlConnection.setRequestProperty("Accept-Encoding", "identity");

设置Accept-Encoding请求标头会显式禁用 自动解压缩,并保持响应头完整无缺; 呼叫者必须根据需要处理减压 Content-Encoding响应的标题.

Setting the Accept-Encoding request header explicitly disables automatic decompression and leaves the response headers intact; callers must handle decompression as needed, according to the Content-Encoding header of the response.

getContentLength()返回已传输的字节数,并且不能 用于预测可以从getInputStream()读取多少个字节 用于压缩流.相反,请读取该流,直到 精疲力尽,即read()返回-1时.

getContentLength() returns the number of bytes transmitted and cannot be used to predict how many bytes can be read from getInputStream() for compressed streams. Instead, read that stream until it is exhausted, i.e. when read() returns -1.

响应是否被压缩当然取决于服务器.

Whether or not the response then actually is compressed depends on the server of course.

这篇关于Android getContentLength在下载apk文件时始终返回-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆