How to know the size of a file before downloading it?
you can get a header called Content-Length
form the HTTP Response object that you get, this will give you the length of the file.
you should note though, that some servers don't return that information, and the only way to know the actual size is to read everything from the response.
Example:
URL url = new URL("http://server.com/file.mp3");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
you can usually use getContentLength , but the best thing is it get the length by yourself (since it can bypass integer's max value) .
just parse the content-length header value by yourself . better parse it as long .
example:
final URL uri=new URL(...);
URLConnection ucon;
try
{
ucon=uri.openConnection();
ucon.connect();
final String contentLengthStr=ucon.getHeaderField("content-length");
//...
}
catch(final IOException e1)
{
}
do note that i can be any string , so use try catch , and if it's -1, empty , or null , it means that you can't know the size of the file since the server doesn't allow it.
EDIT: Here's a more updated code, using 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()) -1 else contentLengthStr.toLong()
} catch (ignored: Exception) {
} finally {
if (urlConnection is HttpURLConnection)
urlConnection.disconnect()
}
return -1
}