I am trying to download a file (mp3) from my server.
I want to show the download process, but you are facing a problem that the file size is -1 all the time.
Screenshot: 
My code is:
try { URL url = new URL(urls[0]); // URLConnection connection = url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); int fileSize = connection.getContentLength(); if (fileSize == -1) fileSize = connection.getHeaderFieldInt("Length", -1); InputStream is = new BufferedInputStream(url.openStream()); OutputStream os = new FileOutputStream(myFile); byte data[] = new byte[1024]; long total = 0; int count; while ((count = is.read(data)) != -1) { total += count; Log.d("fileSize", "Lenght of file: " + fileSize); Log.d("total", "Lenght of file: " + total); // publishProgress((int) (total * 100 / fileSize)); publishProgress("" + (int) ((total * 100) / fileSize)); os.write(data, 0, count); } os.flush(); os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); }
I get the garbage value for fileSize that return -1 ( int fileSize = connection.getContentLength(); )
source share