【问题标题】:Android Http ContentLength always -1Android Http ContentLength 始终为 -1
【发布时间】:2014-09-05 08:56:56
【问题描述】:

我需要一种方法来确定 Internet 上文件的大小。这是我的方法:

    private int getSize(String url){
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        //connection.setConnectTimeout(TIMEOUT);
        //connection.setReadTimeout(TIMEOUT);
        //connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        int size = connection.getContentLength();

        if(responseCode != 200){
            Log.e(LOG_TAG, "Fehlercode: " + responseCode + " beim Ermitteln der Dateigroesse von " + url);
            return -1;
        }

        return size;            
    } catch (IOException e) {
        Log.e(LOG_TAG, "Fehler beim Ermitteln der Dateigroesse von " + url, e);
        return -1;
    }
}

对于 Java(桌面),该方法有效 - 在 Android 上无效。 这有什么问题?

感谢您的帮助!

【问题讨论】:

  • 它会与 fehler 一起返回吗?
  • 是 te contentLength -1 还是你方法的返回值 -1?
  • “connection.getContentLength();”是 -1 并且 responseCode 是 200

标签: java android http content-length


【解决方案1】:

HttpURLConnection和服务交互使用“gzip”压缩(android2.2及更高版本) 你应该设置:

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

参考API: 默认情况下,HttpURLConnection 的这个实现请求服务器使用 gzip 压缩。由于 getContentLength() 返回传输的字节数,因此您无法使用该方法预测可以从 getInputStream() 读取多少字节。相反,读取该流直到它耗尽:whenread() 返回 -1。

【讨论】:

    猜你喜欢
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    相关资源
    最近更新 更多