【问题标题】:Can't get content-length from GoogleWeather API无法从 GoogleWeather API 获取内容长度
【发布时间】:2012-05-04 21:53:03
【问题描述】:

我有一个 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;
        }
    }

我能做什么?或者有没有其他方法可以显示下载数据的进度?

【问题讨论】:

    标签: java android web weather


    【解决方案1】:

    问题出在android的HttpUrlConnection实现机制上。这里是what the official documentation says

    默认情况下,HttpURLConnection 的这种实现要求服务器使用 gzip 压缩。由于getContentLength() 返回传输的字节数,因此您无法使用该方法预测可以从getInputStream() 读取多少字节。相反,读取该流直到它耗尽:当read() 返回-1。可以通过在请求标头中设置可接受的编码来禁用 Gzip 压缩:

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

    【讨论】:

      【解决方案2】:

      页面和其他文件通常不带有 Content-Length 标头(作为“数据块”发送)。在这种情况下,通常浏览器不会显示百分比,而是显示一个永久的动画栏(“// // // // //”)。

      当然,当您知道站点的平均响应时间和客户端的传输速度慢时,您总是可以伪造它。

      【讨论】:

      • 在这种特殊情况下,谷歌天气实际上返回 Content-length 标头
      • @VladimirVolodin 你得到了我的支持,因为你指出了一个 API 错误。禁用压缩并不好。显示的内容长度为 -1 吗?
      猜你喜欢
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 2013-12-26
      相关资源
      最近更新 更多