getContentLength()為-1 解決方法


最近在做一個下載平台,用到多線程下載和斷點續傳功能,當我獲取文件大小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" ); 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM