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!