如何对异步执行的htt prequest并显示在下载响应的进展 [英] How to asynchronous perform a httprequest and show the progress of downloading the response

查看:203
本文介绍了如何对异步执行的htt prequest并显示在下载响应的进展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图执行一个HTTP-GET请求,并显示下载进度给用户。我熟悉的AsyncTask的概念,我也知道如何的URLConnection一起使用具有的BufferedInputStream下载文件碎片而呈现出进步,我知道如何执行HTTP-GET请求和接收的Htt presponse:

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);

但我就是无法弄清楚如何显示执行方法的进展情况。我发现下面的方法。但什么是从InputStream到OutputStream这一切的复制,之后所有的数据都已经下载?我不希望看到这个复制过程的进展,但Htt的presponse的进步! - 有什么建议么?哪里是我的推理错误?我有我错过了什么了强烈的感觉很重要......

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();
}

感谢您!

推荐答案

这code看起来不错。该InputStream为数据的,你下载流。当你下载的每个块,您保存块到一​​个文件中,并更新你的进步。这不是后的数据已经下载。

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.

这篇关于如何对异步执行的htt prequest并显示在下载响应的进展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆