How to asynchronous perform a httprequest and show the progress of downloading the response

江枫思渺然 提交于 2020-01-13 05:54:06

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/9594318/how-to-asynchronous-perform-a-httprequest-and-show-the-progress-of-downloading-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!