PowerShell HttpClient with proxy

Viewed 24

I am using a HttpClient to post a request to a webservice. I am behind a proxy and it seems that the proxy is not used and therefore the request fails.

First I try to define the system proxy to use:

Add-Type -AssemblyName 'System.Net.Http'
$httpClientHandler = New-Object System.Net.Http.HttpClientHandler
$httpClientHandler.UseDefaultCredentials = $true
$httpclientHandler.Proxy = [System.Net.WebRequest]::DefaultWebProxy
$httpClientHandler.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

After that I construct a HttpClient with the previously created Handler:

$client = New-Object System.Net.Http.HttpClient $httpClientHandler
$content = New-Object System.Net.Http.MultipartFormDataContent
$fileStream = [System.IO.File]::OpenRead($file)
$fileName = [System.IO.Path]::GetFileName($file)
$fileContent = New-Object System.Net.Http.StreamContent($fileStream)
$content.Add($fileContent, $fieldName, $fileName)
$result = $client.PostAsync($Url, $content).Result

But it seems that the proxy is not used because I get errors in accessing the url.

Do I need to set anything else?

1 Answers

I was able to find the solution. Something did not work with getting the DefaultWebProxy from system. So I changed it to setting it explicit:

$proxyObject = New-Object System.Net.WebProxy('http://proxy.local:75/')
$httpclientHandler.Proxy = $proxyObject
Related