Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/225.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Can';无法从Google Weather API获取内容长度_Java_Android_Web_Weather - Fatal编程技术网

Java Can';无法从Google Weather API获取内容长度

Java Can';无法从Google Weather API获取内容长度,java,android,web,weather,Java,Android,Web,Weather,我有一个Android应用程序,我想为下载的天气数据显示一个进度条。我将展示大约5个地方的天气预报。问题是当我想从响应头获取内容长度时。日志总是显示我-1(这意味着该字段没有在URLConnection变量中设置) 这是我正在使用的代码: private class DownloadWeatherData extends AsyncTask<String, Integer, String> { @Override protected String do

我有一个Android应用程序,我想为下载的天气数据显示一个进度条。我将展示大约5个地方的天气预报。问题是当我想从响应头获取内容长度时。日志总是显示我-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;
        }
    }
私有类下载WeatherData扩展异步任务{
@凌驾
受保护的字符串背景(字符串…sUrl){
试一试{
URL=新URL(“http://www.google.com/ig/api?weather=NY&hl=en&oe=utf-8");
URLConnection=url.openConnection();
int dataLenght=connection.getContentLength();
Log.d(“ANDRO_ASYNC”,“数据长度:+dataLenght”);
InputStream输入=新的BufferedInputStream(url.openStream());
字节数据[]=新字节[1024];
长总计=0;
整数计数;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
Log.d(“ANDRO_ASYNC”,“int”((count));
}
input.close();
}捕获(例外e){
}
返回null;
}
}

我能做什么?或者是否有其他方式来显示下载数据的进度?

通常,页面和其他文件都没有使用内容长度标题(作为“数据块”发送)。在这种情况下,浏览器通常不显示百分比,而是显示一个永久的动画条(“
////
”)


当然,当你知道站点的平均响应时间和客户端的传输速度时,你总是可以假装它

问题在于android的
HttpUrlConnection
实现机制。这是:

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


urlConnection.setRequestProperty(“接受编码”、“标识”)

在这种特殊情况下,google weather实际上返回内容长度header@VladimirVolodin你得到我的支持,因为我指出了一个API错误。禁用压缩并不好。显示的内容长度是-1?