使用PowerShell的HttpClient下载1.3GB文件时触发‘任务已取消’错误
.NET HttpClient下载大文件时"任务被取消"的解决方法
问题重现
尝试通过PowerShell调用.NET HttpClient对象(而非Invoke-RestMethod)下载1.3GB的ISO文件,编写代码如下:
using namespace System.Net.Http $username = "joedirt" $password = "mypassword" $baseUrl = "https://mywebsite.com/artifactory/api/storage/" $repository = "my-repo" $path = "filename.iso" $outputFilePath = "C:\Users\joedirt\Downloads\filename.iso" $httpClient = [System.Net.Http.HttpClient]::new() $uri = [System.Uri]::new(($baseUrl, $repository, $path -join '/')) $httpClient.DefaultRequestHeaders.Authorization = [System.Net.Http.Headers.AuthenticationHeaderValue]::new( "Basic", [System.Convert]::ToBase64String( [System.Text.Encoding]::ASCII.GetBytes( ($username + ":" + $password) ) ) ) $response = $httpClient.GetAsync($uri).GetAwaiter().GetResult() if ($response.IsSuccessStatusCode){ $fileStream = [System.IO.FileStream]::new($outputFilePath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None) $responseStream = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult() $buffer = [byte[]]::new(8192) while (([int]$bytesRead = $responseStream.Read($buffer, 0, $buffer.Length)) -gt 0){ $fileStream.Write($buffer, 0, $bytesRead) } [System.Console]::WriteLine("File downloaded successfully.") } else { [System.Console]::WriteLine("Failed to download file. StatusCode: $($response.StatusCode)") }
执行到$response = $httpClient.GetAsync($uri).GetAwaiter().GetResult()时,程序停顿数分钟后抛出错误:
Exception calling "GetResult" with "0" argument(s): "A task was canceled."
但使用Invoke-RestMethod从同一URL可以正常下载该文件。
解决方案
问题根源是HttpClient默认超时时间(100秒)不足以完成1.3GB大文件的下载,只需调整超时时间即可解决:
在初始化HttpClient后添加超时配置:
$httpClient.Timeout = [System.TimeSpan]::new(0, 20, 0) # 设置为20分钟
调整后即可成功完成大文件下载。
内容的提问来源于stack exchange,提问作者jerdub1993
相关产品推荐
相关产品推荐

