最近在做一個下載平台,用到多線程下載和斷點續傳功能,當我獲取文件大小getContentLength()的時候,返回結果是-1。文件下載是沒問題的,但是大小卻不正常,用模擬器獲取getContentLength()是正常的,但是真機卻返回-1了,模擬器是低版本運行,於是我就猜想是版本問題,果然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中設置如下參數即可:c
onnection
.
setRequestProperty
(
"Accept-Encoding"
,
"identity"
);