2

I am trying to perform a http-get-request and show the download progress to the user. I am familiar with the concept of AsyncTask, I also know how to use URLConnection together with BufferedInputStream to download a file in pieces while showing a progress AND I know how to execute a http-get-request and receive a HttpResponse:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);

But I just cannot figure out how to show a progress of the execute method. I found the method below. But what is all this copying from an InputStream to an OutputStream, after all data are already downloaded? I don't want to see the progress of this copying process, but the progress of the HttpResponse! - Any suggestions? Where is my error in reasoning? I have the strong feeling that I missed something very important ...

String sURL = getString(R.string.DOWNLOAD_URL) + getString(R.string.DATABASE_FILE_NAME);
HttpClient  httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(sURL);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
Header[] clHeaders = response.getHeaders("Content-Length");
Header header = clHeaders[0];
int totalSize = Integer.parseInt(header.getValue());
int downloadedSize = 0;
if (entity != null) {
    InputStream stream = entity.getContent();
    byte buf[] = new byte[1024 * 1024];
    int numBytesRead;

    BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
    do {
        numBytesRead = stream.read(buf);
        if (numBytesRead > 0) {
            fos.write(buf, 0, numBytesRead);
            downloadedSize += numBytesRead;
            //updateProgress(downloadedSize, totalSize);
        }
    } while (numBytesRead > 0);
    fos.flush();
    fos.close();
    stream.close();
    httpclient.getConnectionManager().shutdown();
}

Thank you!

Thassilo
  • 309
  • 1
  • 4
  • 12

1 Answers1

2

That code looks fine. The InputStream is the stream of data that you're downloading. As you download each chunk, you save that chunk into a file and update your progress. It's not after the data is already downloaded.

kabuko
  • 36,028
  • 10
  • 80
  • 93
  • Ah - thanks! So I was just confused, because of the delay of the execute method. But that actually comes from the work to send the request and receive header; am I correct now? – Thassilo Mar 07 '12 at 01:21
  • Yep, sounds right. If you want, you can compare with downloading some very large files and see. That pause at the beginning should still be about the same length and then you should see the progress update as expected. – kabuko Mar 07 '12 at 01:24