HttpClient 直接下载文件,如果文件比较大,没有进度显示会很不友好,
所有在下载的时候希望下载一部分就显示一下进度。
代码的重点是
HttpCompletionOption.ResponseHeadersRead以及
ReadAsStreamAsync
对于dispose,也可以用using。
var saveFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); var fs = await saveFile.OpenAsync(FileAccessMode.ReadWrite); HttpClientHandler handler = new HttpClientHandler(); handler.ClientCertificateOptions = ClientCertificateOption.Automatic; HttpClient hc = new HttpClient(handler); HttpResponseMessage response = await hc.GetAsync(DownUrl, HttpCompletionOption.ResponseHeadersRead); Stream stream = await response.Content.ReadAsStreamAsync(); IInputStream inputStream = stream.AsInputStream(); ulong totalBytesRead = 0; while (true) { // Read from the web. IBuffer buffer = new Buffer(1024); buffer = await inputStream.ReadAsync( buffer, buffer.Capacity, InputStreamOptions.None); if (buffer.Length == 0) { // 完成 break; } // 进度 totalBytesRead += buffer.Length; System.Diagnostics.Debug.WriteLine("Bytes read: {0}", totalBytesRead); // 写文件. await fs.WriteAsync(buffer); } inputStream.Dispose(); fs.Dispose();