下載網絡文件HttpURLConnection.getContentLength()大小爲 -...

     作一個andriod系統,測試的時候是在android 2.2系統上測試的一切正常,等發佈的時候發現個小問題,就是當程序有更新時,須要從新下載APK,爲了友好,作了個進度條,可是在 2.2以上的系統中進度條不會走動,部分代碼以下: android

   HttpURLConnection conn = (HttpURLConnection)url.openConnection();    conn.connect(); ide

 int length = conn.getContentLength(); 測試

   InputStream is = conn.getInputStream(); this


    通過debug,發現是因爲,conn.getContentLength() 時獲取到的值爲 -1,致使計算進度時,結果有誤,永遠爲負數。在網上查資料都說是服務端沒有設content length,跟服務端協商,加上這個就好了。可是爲毛2.2,的時候就能夠服務端也沒設啊,查API :Returns the content length in bytes specified by the response header field content-length or -1 if this field is not set.看API也彷佛是這個意思。原本打算投降了,跟服務端商量下,看能不能主動加上。忽然手賤多點了下查找,發現這麼一段話: url

      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。 spa

彷佛是說,在默認狀況下,HttpURLConnection 使用 gzip方式獲取,文件 getContentLength() 這個方法,每次read完成後能夠得到,當前已經傳送了多少數據,而不能用這個方法獲取 須要傳送多少字節的內容,當read() 返回 -1時,讀取完成,因爲這個壓縮後的總長度我沒法獲取,那麼進度條就無法計算值了。 debug

要取得長度則,要求http請求不要gzip壓縮,具體設置以下 code

HttpURLConnection conn = (HttpURLConnection)url.openConnection(); server

conn .setRequestProperty("Accept-Encoding", "identity"); 
conn.connect();

int length = conn.getContentLength(); ip

InputStream is = conn.getInputStream();

相關文章
相關標籤/搜索