HttpClient下载文件内存不足错误
本文关键字:错误 内存不足 文件 下载 HttpClient | 更新日期: 2023-09-27 17:58:46
你好,我将此代码用于文件下载功能,但由于我的文件大小较大,收到了OutOfMemory异常。
private async void DownloadFile()
{
string url = "http://download.microsoft.com/download/0/A/F/0AFB5316-3062-494A-AB78-7FB0D4461357/Windows_Win7SP1.7601.17514.101119-1850.AMD64CHK.Symbols.msi";
string filename = "test.msi";
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.
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
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);
buffer = null;
}
inputStream.Dispose();
fs.Dispose();
}
PS。我使用httpclient下载,但Windows手机后台传输有100MB的wifi限制。
我在去年编写的一些不同的代码中遇到了同样的问题,尽管那是POST
而不是GET
。不幸的是,我没有找到绕过它的方法,所以我直接使用WebRequest
。以下是修复的片段:
// HttpWebRequest is used here instead of HttpClient as there is no support
// in HttpClient to not buffer uploaded streams, which for our purposes
// causes an OutOfMemoryException to occur.
HttpWebRequest request = WebRequest.Create(ServiceUri.ToString() + requestUri) as HttpWebRequest;
request.ContentLength = content.Length;
request.ContentType = "application/octet-stream";
request.Method = "POST";
request.AllowWriteStreamBuffering = false; // Prevents OutOfMemoryException
我认为您的解决方案是在使用HttpClient
下载时以某种方式禁用缓冲。