title: Download file in java when Content-Length is incorrectly set?
body: <p>I have an android app that downloads and uses a file at runtime. The file is valid as I can download it via the browser and open it up, etc. However my app kept reporting that the file is corrupted. </p>
  
  <p>After investigation I discovered the server (which I have no control over) is returning an incorrect "Content-Length:" (~180 vs ~120000). The header is the culprit as I confirmed the issue by downloading the file with curl - which also resulted in a truncated file.</p>
  
  <p>After some research I concluded that my use of <code>BufferedInputStream</code> to append to a <code>ByteArrayBuffer</code> is autosizing the byte array to the url connections content length. To circumvent this, I tried to use <code>ByteArrayOutputStream</code> instead, however this solved nothing. </p>
  
  <p>Anybody know of a way to download a file if the Content-Length is incorrectly set? A browser can.</p>
  
  <p>Here's my latest attempt:</p>
  
  <pre><code>public static void downloadFileFromRemoteUrl(String urlString, String destination){
      try {
          URL url = new URL(urlString);
          File file = new File(destination);
          URLConnection urlConnection = url.openConnection();
          InputStream inputStream = urlConnection.getInputStream();
          byte[] buffer = new byte[1024];
          int curLength = 0;
          int newLength = 0;
          ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
          while((newLength = inputStream.read(buffer))&gt;0)
          {
              curLength += newLength;
              byteArrayOutputStream.write(buffer, 0, newLength);
          }
          FileOutputStream fos = new FileOutputStream(file);
          fos.write(byteArrayOutputStream.toByteArray());
          fos.close();
          android.util.Log.d("DB UPDATE", "Done downloading database. Size: " + byteArrayOutputStream.toByteArray().length);
      }
      catch (MalformedURLException e) {
          e.printStackTrace();
      }
      catch (IOException e) {
          e.printStackTrace();
      }
  }
  </code></pre>