jerdub1993
jerdub1993

Reputation: 475

File downloaded with HttpClient is failing with error 'A task was cancelled'

I'm trying to download a 1.3GB file with PowerShell using .NET objects instead of Invoke-RestMethod, but I'm not very well-versed in Memory/FileStreams. Here's my code:

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)")
}

When it gets to $response = $httpClient.GetAsync($uri).GetAwaiter().GetResult(), it pauses for a while (a couple of minutes), which makes me believe it's downloading, but then fails with error:

Exception calling "GetResult" with "0" argument(s): "A task was canceled."

I'm able to download the same file from the same URL with Invoke-RestMethod, but I'm not sure why the HttpClient method isn't working.

Edit: As pointed out by @dawid-nowak, the httpClient.Timeout was what stopped it. I upped the Timeout and it finished successfully:

$httpClient.Timeout = [System.TimeSpan]::new(0, 20, 0)

Upvotes: 0

Views: 430

Answers (1)

Dawid
Dawid

Reputation: 102

Maybe the timeout kicks in, according to this, http client has default timeout set to 100 seconds.

Check if you can set it to some higher values like 5 minutes.

Upvotes: 1

Related Questions