Android getContentLength()為-1 解決方法


  公司的sdk要做一個app下載功能。開始使用的安智的下載鏈接,程序一直運行正常。但是公司自己的服務器的時候,就報錯了。因為要獲取文件大小來做進度條,錯誤位置是在獲取文件大小getContentLength()的時候返回-1.對比了一下請求的response,發現就是沒有返回文件的ContentLength.  

 

  網上搜了一下,加入代碼

HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn .setRequestProperty("Accept-Encoding", "identity"); 
conn.connect();


發現可以了。

原因:

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: when read() returns -1. Gzip compression can be disabled by setting the acceptable encodings in the request header。

似乎是說,在默認情況下,HttpURLConnection 使用 gzip方式獲取,文件 getContentLength() 這個方法,每次read完成后可以獲得,當前已經傳送了多少數據,而不能用這個方法獲取 需要傳送多少字節的內容,當read() 返回 -1時,讀取完成,由於這個壓縮后的總長度我無法獲取,那么進度條就沒法計算值了。

要取得長度則,要求http請求不要gzip壓縮。

參考:

http://www.cnblogs.com/helloandroid/archive/2013/01/21/2869776.html

http://my.oschina.net/u/133352/blog/96582

 

 


免責聲明!

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



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