本文介绍了如何使用Invoke-RestMethod从PowerShell发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据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

推荐答案

TL;DR:

该错误消息极具误导性,而且毫无帮助。但是,在查看代码之后,$body看起来不像是有效的json。更仔细地看,PowerShell documentation提到,即使您指定了所需的ContentType

,它也不会自动转换它

所以您仍然需要自己进行转换:

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

这篇关于如何使用Invoke-RestMethod从PowerShell发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 12:48