簡體   English   中英

無法從GoogleWeather API獲取內容長度

[英]Can't get content-length from GoogleWeather API

我有一個Android應用程序,我想顯示下載的天氣數據的進度條。 我將顯示大約5個地方的天氣預報。 問題是當我想從響應頭獲取Content-Length時。 日志總是顯示-1(表示該字段未在URLConnection變量中設置)。

這是我正在使用的代碼:

private class DownloadWeatherData extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... sUrl) {
            try {
                URL url = new URL("http://www.google.com/ig/api?weather=NY&hl=en&oe=utf-8");
                URLConnection connection = url.openConnection();

                int dataLenght = connection.getContentLength();
                Log.d("ANDRO_ASYNC", "Data lenght: " + dataLenght);

                InputStream input = new BufferedInputStream(url.openStream());

                byte data[] = new byte[1024];
                long total = 0;
                int count;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    Log.d("ANDRO_ASYNC", ""+(int)((count)));
                }
                input.close();
            } catch (Exception e) {
            }
            return null;
        }
    }

我能做什么? 或者是否有其他方式顯示下載數據的進度?

問題出在android的HttpUrlConnection實現機制中。 以下是官方文檔所說的內容

默認情況下, HttpURLConnection此實現請求服務器使用gzip壓縮。 由於getContentLength()返回傳輸的字節數,因此您無法使用該方法來預測可從getInputStream()讀取的字節數。 相反,讀取該流直到它耗盡:當read()返回-1時。 可以通過在請求標頭中設置可接受的編碼來禁用Gzip壓縮:

urlConnection.setRequestProperty("Accept-Encoding", "identity");

通常,頁面和其他文件不會隨Content-Length標頭一起提供(作為“數據塊”發送)。 在這種情況下,通常瀏覽器不顯示百分比,而是顯示永久動畫欄(“ // // // // // ”)。

當然,在了解網站的平均響應時間和傳輸客戶端的緩慢時,您總是可以偽造它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM