Rob*_*MBA 1 powershell powershell-3.0 invoke-restmethod
根据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;
Run Code Online (Sandbox Code Playgroud)
我的错误是
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
Run Code Online (Sandbox Code Playgroud)
错误消息极具误导性,根本没有帮助。在查看代码后,虽然$body看起来不是有效的 json。更仔细地看,PowerShell 文档提到它不会自动转换它,即使您指定了所需的ContentType:
对于其他请求类型(例如 POST),主体设置为标准 name=value 格式的请求主体的值。
所以你仍然需要自己转换它:
Invoke-RestMethod -Method 'Post' -Uri $uri -ContentType 'application/json' -Body ($body | ConvertTo-Json);
Run Code Online (Sandbox Code Playgroud)
我建立了一个快速测试台来验证我的假设:
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();
}
Run Code Online (Sandbox Code Playgroud)
您的原始代码示例返回如下:
Client data content type application/json
Start of client data:
Name=simPass2&Status=Complete
---------------------
Run Code Online (Sandbox Code Playgroud)
但如果你使用ConvertTo-Json,结果看起来更好:
Client data content type application/json
Start of client data:
{
"Name": "simPass2",
"Status": "Complete"
}
---------------------
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1294 次 |
| 最近记录: |