Java HTTPConnection recupera el tamaño del archivo antes de descargar

I am trying to download a large (11MB) JSON file from a web service using this code:

public static void downloadBigFile(final String serverUrl,
        final String fileName) throws MalformedURLException, IOException {
    System.out.println("Downloading " + serverUrl + " (" + fileName + ")");

    URL url = new URL(serverUrl);
    URLConnection con = url.openConnection();
    con.setConnectTimeout(10000);
    con.setReadTimeout(2 * 60 * 1000);

    int totalFileSize = con.getContentLength();
    System.out.println("Total file size: " + totalFileSize);

    InputStream inputStream = con.getInputStream();
    FileOutputStream outputStream = new FileOutputStream(fileName);

    // Used only for knowing the amount of bytes downloaded.
    int downloaded = 0;

    final byte[] buffer = new byte[1024 * 8];
    int bytesRead;

    bytesRead = inputStream.read(buffer);

    while (bytesRead != -1) {
        downloaded += bytesRead;
        outputStream.write(buffer, 0, bytesRead);
        bytesRead = inputStream.read(buffer);

        System.out.println(String.format("%d/%d (%.2f%%)", downloaded,
                totalFileSize,
                (downloaded * 1.0 / totalFileSize * 1.0) * 100));
    }

    System.out
            .println(fileName + " downloaded! (" + downloaded + " bytes)");

    inputStream.close();
    outputStream.close();
}

Sin embargo, la llamada a con.getContentLength() blocks the thread for several minutes, while it downloads the whole file I presume.

The problem is I need a quick way to discover file size before the download starts so I can notify the user accordingly.

Nota: already tried to call con.connect() y con.getHeaderField("Content-Length").

preguntado el 26 de septiembre de 13 a las 20:09

1 Respuestas

If the server does not specify the Content-Length header, the only way to get the content length is to download the whole file and see how big it is.

Respondido el 26 de Septiembre de 13 a las 20:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.