HttpClient的进度栏

我有一个文件下载功能:

        HttpClientHandler aHandler = new HttpClientHandler();

aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;

HttpClient aClient = new HttpClient(aHandler);

aClient.DefaultRequestHeaders.ExpectContinue = false;

HttpResponseMessage response = await aClient.GetAsync(url);

InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();

// To save downloaded image to local storage

var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(

filename, CreationCollisionOption.ReplaceExisting);

var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);

DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));

writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());

await writer.StoreAsync();

//current.image.SetSource(randomAccessStream);

writer.DetachStream();

await fs.FlushAsync();

如何实现进度条功能?也许我可以到目前为止写出作家的字节数?或者其他的东西?

回答:

最好的方法是使用Windows.Web.Http.HttpClient而不是System.Net.Http.HttpClient。第一个支持进度。

但是,如果由于某种原因您想坚持使用System.Net,则需要实现自己的进度。

删除DataWriter,删除InMemoryRandomAccessStream

以便它在收到标头后立即返回,而不是在收到整个响应时返回。即:

// Your original code.

HttpClientHandler aHandler = new HttpClientHandler();

aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;

HttpClient aClient = new HttpClient(aHandler);

aClient.DefaultRequestHeaders.ExpectContinue = false;

HttpResponseMessage response = await aClient.GetAsync(

url,

HttpCompletionOption.ResponseHeadersRead); // Important! ResponseHeadersRead.

// To save downloaded image to local storage

var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(

filename,

CreationCollisionOption.ReplaceExisting);

var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);

// New code.

Stream stream = await response.Content.ReadAsStreamAsync();

IInputStream inputStream = stream.AsInputStream();

ulong totalBytesRead = 0;

while (true)

{

// Read from the web.

IBuffer buffer = new Windows.Storage.Streams.Buffer(1024);

buffer = await inputStream.ReadAsync(

buffer,

buffer.Capacity,

InputStreamOptions.None);

if (buffer.Length == 0)

{

// There is nothing else to read.

break;

}

// Report progress.

totalBytesRead += buffer.Length;

System.Diagnostics.Debug.WriteLine("Bytes read: {0}", totalBytesRead);

// Write to file.

await fs.WriteAsync(buffer);

}

inputStream.Dispose();

fs.Dispose();

以上是 HttpClient的进度栏 的全部内容, 来源链接: utcz.com/qa/409229.html

回到顶部