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中設置如下參數即可:connection.setRequestProperty("Accept-Encoding","identity"); 
經檢驗,可行

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章