Search code examples
javaurlfile-ioapache-commons

Methods for downloading files from a URL in Java


I want to download a binary file from a webserver which is running on a embedded device. That file can be downloaded manually after a basic http authentication by using that URL: http://10.10.10.10/config.bin... Now i want to automate this process with a simple Java application. By using the basic java tools i managed to download the file:

URL mlrrl = new URL(url);
            HttpURLConnection  con = (HttpURLConnection) mlrUrl.openConnection();

            con.setRequestMethod("GET");
            con.setAllowUserInteraction(false);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setConnectTimeout(10000);
            con.setRequestProperty("Authorization", "Basic " + authStringEnc);

            InputStream stream = con.getInputStream();
            BufferedInputStream in = new BufferedInputStream(stream);
            FileOutputStream file = new FileOutputStream("configDown.bin");
            BufferedOutputStream out = new BufferedOutputStream(file);
            int i;
            while ((i = in.read()) != -1) {
                out.write(i);
            }
            out.flush();

That seemed to work fine! In comparison with the manually (by Browser-Webinterface) downloaded file the generated file have the same length, but after opening both binaries with a hex-editor they were different.

My questions:

  1. Any ideas why the hex-codes are different? (Maybe missing connection properties?)
  2. There is a copyUrlToFile-Method in the apache.commons package. Is it possible to use it with basic http authentification, as a alternative?
  3. Are there other java libs or tools for downloading files from urls?

Solution

  • I can´t explain why, but the faulty property "setDoOutput" = "true" maybe influenced the content of the downloaded file. Setting the value to "false" solved that issue for me!