gpt4 book ai didi

java - Android Http ContentLength 始终为 -1

转载 作者:行者123 更新时间:2023-12-02 05:29:34 25 4
gpt4 key购买 nike

我需要一种方法来确定 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 上则无效。这有什么问题吗?

感谢您的帮助!

最佳答案

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

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

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

关于java - Android Http ContentLength 始终为 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25682102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com