http urlconnection getcontentlength總返回值為-1

yangxi_001發表於2015-07-06

最近在做一個自動更新的功能,點選更新下載之後,進度條不走動。之前一直用的模擬器執行,沒有發現任何問題,後來真機測試時就出現了進度條不走動的問題。經斷點除錯發現,當獲取下載檔案大小getContentLength()的時候,返回結果是-1。於是上網搜了一下HttpURLConnection及getContentLength(),發現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中設定如下引數即可:conn.setRequestProperty(“Accept-Encoding”, “identity”);

相關文章