如何将Powers shell System.Net.Http.Httpclient调用转换为Invoke-RestMethod

时间:2018-01-12 21:22:02

标签: powershell httpclient

我有以下代码正在运行。但我的要求是我不能使用System.Net.Http.Httpclient。我必须将其转换为Invoke-RestMethod -Method Post。以下代码工作正常。

# Add the necessary .NET assembly
Add-Type -AssemblyName System.Net.Http
# Create the HttpClient client
$client = New-Object -TypeName System.Net.Http.Httpclient
$client.BaseAddress = $sasHost; 
$action = '/system/collection';
$stringcontent =  New-Object System.Net.Http.StringContent($json, 
     [System.Text.Encoding]::UTF8, "application/json");
$response = $client.PostAsync($action, $stringcontent).Result;
# If it is failed 
if($response.IsSuccessStatusCode -eq $false)
{
    write-host $response.StatusCode -foregroundcolor "Red";
}

我尝试了以下内容。但它引发了一个例外。我怀疑我的转换不正确。因为上面的代码工作正常。我不知道如何正确地做到这一点。

$url = ($sasHost, $action  -join "");
try
{
    Invoke-RestMethod -Method Post -Uri $url -ContentType "application/json" -Body $stringcontent
    write-host "Collection bootstrapping done successfully" -foregroundcolor DarkMagenta -BackgroundColor Green;
}
catch [Exception]
{
    Write-Host "Exception: "$_.Exception.Message -ForegroundColor Red;
}
  

$ _.Exception.Message远程服务器返回错误:(500)   内部服务器错误。

0 个答案:

没有答案