我需要下载一个文件,使用的是这段代码,它基本上是一个AsyncTask
,用于更新进度条。但是,由于我不知道文件大小,因此一直在使用旋转进度条。那么,我该如何在开始下载文件之前获取文件大小,以便使用普通进度条呢?
您可以从获得的HTTP响应对象中获取名为Content-Length
的标头,这将告诉您文件的长度。
需要注意的是,有些服务器不返回该信息,唯一知道实际大小的方法是从响应中读取所有内容。
示例:
URL url = new URL("http://server.com/file.mp3");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
你通常可以使用getContentLength,但最好自己获取长度(因为它可以绕过整数的最大值)。
自己解析content-length头部的值。最好将其解析成长整型。
示例:
final URL uri=new URL(...);
URLConnection ucon;
try
{
ucon=uri.openConnection();
ucon.connect();
final String contentLengthStr=ucon.getHeaderField("content-length");
//...
}
catch(final IOException e1)
{
}
请注意,变量i可以是任何字符串,因此请使用try-catch语句。如果i的值为-1、空或null,则意味着您无法知道文件的大小,因为服务器不允许。
编辑:以下是使用Kotlin更新后的代码:
@JvmStatic
@WorkerThread
fun getFileSizeOfUrl(url: String): Long {
var urlConnection: URLConnection? = null
try {
val uri = URL(url)
urlConnection = uri.openConnection()
urlConnection!!.connect()
if (VERSION.SDK_INT >= Build.VERSION_CODES.N)
return urlConnection.contentLengthLong
val contentLengthStr = urlConnection.getHeaderField("content-length")
return if (contentLengthStr.isNullOrEmpty()) -1L else contentLengthStr.toLong()
} catch (ignored: Exception) {
} finally {
if (urlConnection is HttpURLConnection)
urlConnection.disconnect()
}
return -1L
}
urlConnection.connect()
。不这样做可能会起作用,但并非在所有可能的情况下都是如此。 - Felix