1

根据https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-7#example-2--run-a-post-request我是试图调用一个简单的 POST 方法但得到一些错误。

我的指示是:

$uri = "https://localhost:44355/api/job/machine-status";
#$machineName = HOSTNAME.EXE;
$machineName = "simPass2";
$body = @{
    Name = $machineName
    Status = "Complete"
}
Invoke-RestMethod -Method 'Post' -Uri $uri  -ContentType 'application/json' -Body $body;

我的错误是

Invoke-WebRequest : Unable to connect to the remote server
At line:8 char:1
+ Invoke-WebRequest -Uri $uri -Method Post -ContentType 'application/js ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Comman
ds.InvokeWebRequestCommand
4

1 回答 1

6

TL;博士:

该错误消息极具误导性,根本没有帮助。在查看代码后,虽然$body看起来不是一个有效的 json。仔细观察,PowerShell 文档提到它不会自动转换它,即使您指定了 desired ContentType

对于其他请求类型(如 POST),body 被设置为标准 name=value 格式的请求 body 的值。

所以你仍然需要自己转换它:

Invoke-RestMethod -Method 'Post' -Uri $uri  -ContentType 'application/json' -Body ($body | ConvertTo-Json);

测试一下

我建立了一个快速测试台来验证我的假设:

void Main()
{
    var listener = new HttpListener(); // this requires Windows admin rights to run
    listener.Prefixes.Add("http://*:8181/"); // this is how you define port and host the Listener will sit at: https://docs.microsoft.com/en-us/dotnet/api/system.net.httplistener?view=netcore-3.1
    listener.Start();
    var context = listener.GetContext();
    var request = context.Request;
    var response = context.Response;
    
    var reader = new System.IO.StreamReader(request.InputStream, Encoding.UTF8);
    Console.WriteLine($"Client data content type {request.ContentType}");   
    Console.WriteLine("Start of client data:"); 
    Console.WriteLine(reader.ReadToEnd());// Convert the data to a string and dump it to console.
    Console.WriteLine("---------------------");
    
    // just fill the response so we can see it on the Powershell side:
    response.StatusCode = 200;
    var buffer = Encoding.UTF8.GetBytes("Nothing to see here");
    response.OutputStream.Write(buffer, 0, buffer.Length);
    response.Close(); // need this to send the response back
    listener.Stop();
}

您的原始代码示例返回如下内容:

Client data content type application/json
Start of client data:
Name=simPass2&Status=Complete
---------------------

但如果您使用ConvertTo-Json,结果看起来会更好:

Client data content type application/json
Start of client data:
{
    "Name":  "simPass2",
    "Status":  "Complete"
}
---------------------
于 2020-07-30T01:37:55.230 回答