PowerShell WebRequest POST

标签 powershell

在 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/

相关文章:

shell - Jenkins Pipeline Access 阶段步骤变量在 powershell 执行中

xml - XPath 查询精确匹配

powershell - 如何在 Windows Bat 或 Powershell 中识别用于成功 ping 的网络适配器(或接口(interface))名称

powershell - powerShell Set-acl奇怪的错误: there is not enough space on the disk

json - "The property cannot be found on this object. Verify that the property exists."属性肯定存在

c# - 从 C# 调用带参数的 PowerShell 脚本

c# - 我可以使用 C# 和 Powershell 做什么?

Powershell由于内存常量而崩溃

powershell - Powershell-使用不同的域凭据从不同位置复制文件

powershell - throw 和 $pscmdlet.ThrowTerminateerror() 之间的区别?