在 Windows PowerShell 3.0 中引入了 Invoke-RestMethod小命令。
Invoke-RestMethod cmdlet 接受 -Body<Object>
用于设置请求正文的参数。
由于某些限制Invoke-RestMethod在我们的案例中无法使用 cmdlet。另一方面,文章 InvokeRestMethod for the Rest of Us 中描述的替代解决方案适合我们的需求:
$request = [System.Net.WebRequest]::Create($url)
$request.Method="Get"
$response = $request.GetResponse()
$requestStream = $response.GetResponseStream()
$readStream = New-Object System.IO.StreamReader $requestStream
$data=$readStream.ReadToEnd()
if($response.ContentType -match "application/xml") {
$results = [xml]$data
} elseif($response.ContentType -match "application/json") {
$results = $data | ConvertFrom-Json
} else {
try {
$results = [xml]$data
} catch {
$results = $data | ConvertFrom-Json
}
}
$results
但它仅适用于 GET 方法。
您能否建议如何扩展此代码示例,使其能够使用
POST
发送请求正文?方法(类似于 Body
中的参数 Invoke-RestMethod
)?
最佳答案
首先,更改更新 HTTP 方法的行。
$request.Method= 'POST';
接下来,您需要将消息正文添加到
HttpWebRequest
目的。为此,您需要获取对请求流的引用,然后向其中添加数据。$Body = [byte[]][char[]]'asdf';
$Request = [System.Net.HttpWebRequest]::CreateHttp('http://www.mywebservicethatiwanttoquery.com/');
$Request.Method = 'POST';
$Stream = $Request.GetRequestStream();
$Stream.Write($Body, 0, $Body.Length);
$Request.GetResponse();
注意 :PowerShell Core版本现已在 GitHub 上开源,并在 Linux、Mac 和 Windows 上跨平台。
Invoke-RestMethod
的任何问题cmdlet 应在此项目的 GitHub 问题跟踪器上报告,以便可以跟踪和修复它们。
关于PowerShell WebRequest POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921529/