Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File downloading - negative file length

Tags:

java

android

I am trying to download a file (mp3) from my server.

I want to show the downloading progress, but I am facing a problem that whole time the file size is -1.

The screenshot: enter image description here
My code:

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 the fileSize which return -1 (int fileSize = connection.getContentLength();)

like image 860
Prosanto Avatar asked May 09 '15 15:05

Prosanto


1 Answers

Inspect the headers the server is sending. Very probably the server is sending Transfer-Encoding: Chunked and no Content-Length header at all. This is a common practice in HTTP/1.1. If the server isn't sending the length, the client obviously can't know it. If this is the case, and you have no control over the server code, the best thing to do is probably display a spinner type of indicator only.

like image 167
kaqqao Avatar answered Nov 04 '22 07:11

kaqqao