Android getContentLength 在下载 apk 文件时总是 return -1

Android getContentLength always return -1 when downloading apk file

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

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

如果 fileUrl 是 apk,lenghtOfFile 总是 return -1.
但是如果是图片,视频类型,... lenghtOfFile return 正好.

为什么?

我正在使用 Eclipse,Android SDK 修订版 23。

内容长度并不总是可用,因为默认情况下 Android 请求 GZIP 压缩响应。资料来源:Android documentation.

引用link:

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");

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() 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.

响应是否实际被压缩当然取决于服务器。