getContentLength() 在某些设备上返回 -1,而在其他设备上则不返回
我试图在下载之前获取文件的大小。我使用 conn.getContentLength(); 来执行此操作,它在我的家用计算机 Android 2.1 模拟器上运行良好。
然而,一旦我从手机(WiFi 或 3G)运行我的应用程序,它就不起作用,并且当我从工作笔记本电脑 Android 2.1 模拟器运行它时,它也不起作用。
有谁知道这个问题的解决方法?有没有其他方法可以在不使用 HttpURLConnection 的情况下获取文件的大小。
I'm trying to obtain the size of a file before I download it. I use conn.getContentLength();
to do this and it works fine on my home computers Android 2.1 Emulator.
It however doesn't work once I run my app from my phone (either WiFi or 3G) and it also doesn't work when I run it from my work laptops Android 2.1 Emulator.
Does anyone know a workaround for this? Is there another way I can obtain the size of the file maybe without using HttpURLConnection
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此信息并不总是可用。通常您会知道正在下载的文件的长度。根据网络服务器、协议、连接和下载方法的不同,此信息可能并不总是可用。
您绝对应该修改您的应用程序,以便它可以处理这种情况。我想您会发现使用不同连接方法的不同设备会提供不同的结果。
This information will not always be available. Usually you will know the length of the file you are downloading. Depending on the webserver, the protocol, the connection, and the method of downloading, this information may not always be available.
You should definitely modify your application so that it can handle this situation. I think you will find that different devices using different connection methods will offer different results with this.
使用
HttpVersion.HTTP_1_0
进行文件下载。这可以防止使用“分块传输编码”请参阅:http://en.wikipedia.org/wiki/Chunked_transfer_encoding
例如,重载构造函数,以便您可以指定哪个 HTTP 版本:
当您想要下载文件时,请使用
HTTPrequest httpRequest = new HTTPrequest(HttpVersion.HTTP_1_0);
以及当您需要时执行 POST 或 GET 使用HTTPrequest httpRequest = new HTTPrequest();
Use
HttpVersion.HTTP_1_0
for your file downloads. This prevents the use of "Chunked transfer encoding"See: http://en.wikipedia.org/wiki/Chunked_transfer_encoding
For example, overload the constructor so that you can specify which HTTP version:
When you want to do a file download use
HTTPrequest httpRequest = new HTTPrequest(HttpVersion.HTTP_1_0);
and when you want to do a POST or GET useHTTPrequest httpRequest = new HTTPrequest();