我想從android中的服務器下載文件並使用代碼非常類似於answer provided in this thread顯示進度對話框,但我無法獲得內容長度HttpURLConnection
的getContentLength()
方法。所有文件的內容長度爲-1。Android HttpURLConnection內容長度
對於同一個文件,我在NSHTTPURLResponse
的expectedContentLength
方法中得到正確的iOS應用內容長度。
這些方法獲取http連接/響應的內容長度的方式有一些基本的區別嗎?
編輯1:
嘗試以下幾件事情的建議一些答案和評論。
- 集
Accept-Encoding
頭identity
- 抓取內容長度的字符串(從報頭字段
Content-Length
),然後將其轉換爲長 - 試過
conn.getContent().toString().length()
代替getContentLength()
無這些工作的對我來說呢。
最讓我感到困惑的是我得到的內容在iOS中的長度,但不是在Android上。
編輯2:
我的繼承人iOS和Android的代碼進行比較 -
的iOS:
NSURLRequest *request = [NSURLRequest requestWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
安卓
URL url = new URL(downloadUrlString);
connection = (HttpURLConnection) url.openConnection();
connection .setRequestProperty("Accept-Encoding", "identity");
connection.connect();
唯一的區別我可以看到正在緩存。 所以我在android代碼中添加了以下代碼,但沒有任何更改。
connection.setUseCaches(true);
檢查此答案http://stackoverflow.com/a/2294899/719212 – R4j
@ R4j我檢查了鏈接。我試過了,但沒有奏效。在該鏈接中的答案對於返回正確內容長度但對於int來說太大的httprequests更有效。我沒有得到任何內容 - lentgth。 – lukya
根據網絡服務器,協議,連接或下載方法的不同,「Content-length」可能並不總是可用。但對於你的情況,我認爲你應該像ios一樣提出請求(檢查你的頭文件,內容類型...)。或者,也許你應該提供你的ios代碼,然後人們可以幫助你。 – R4j