PowerShell WebRequest POST

Vad*_*hev 9 powershell

在Windows PowerShell 3.0中引入了Invoke-RestMethod cmdlet.

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 
Run Code Online (Sandbox Code Playgroud)

但它仅适用于GET方法.您能否建议如何扩展此代码示例,并能够使用POST方法发送请求正文(类似于Body参数Invoke-RestMethod)?

Tre*_*van 18

首先,更改更新HTTP方法的行.

$request.Method= 'POST';
Run Code Online (Sandbox Code Playgroud)

接下来,您需要将消息正文添加到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();
Run Code Online (Sandbox Code Playgroud)

注意:PowerShell核心版现在在GitHub上是开源的,在Linux,Mac和Windows上是跨平台的.Invoke-RestMethod应该在此项目的GitHub问题跟踪器上报告cmdlet的任何问题,以便可以跟踪和修复它们.


Gop*_*lai 5

$myID = 666;
#the xml body should begin on column 1 no indentation.
$reqBody = @"
<?xml version="1.0" encoding="UTF-8"?>
<ns1:MyRequest
    xmlns:ns1="urn:com:foo:bar:v1"
    xmlns:ns2="urn:com:foo:xyz:v1"
    <ns2:MyID>$myID</ns2:MyID>
</ns13:MyRequest>
"@

Write-Host $reqBody;

try
{
    $endPoint = "http://myhost:80/myUri"
    Write-Host ("Querying "+$endPoint)
    $wr = [System.Net.HttpWebRequest]::Create($endPoint)
    $wr.Method= 'POST';
    $wr.ContentType="application/xml";
    $Body = [byte[]][char[]]$reqBody;
    $wr.Timeout = 10000;

    $Stream = $wr.GetRequestStream();

    $Stream.Write($Body, 0, $Body.Length);

    $Stream.Flush();
    $Stream.Close();

    $resp = $wr.GetResponse().GetResponseStream()

    $sr = New-Object System.IO.StreamReader($resp) 

    $respTxt = $sr.ReadToEnd()

    [System.Xml.XmlDocument] $result = $respTxt
    [String] $rs = $result.DocumentElement.OuterXml
    Write-Host "$($rs)";
}
catch
{
    $errorStatus = "Exception Message: " + $_.Exception.Message;
    Write-Host $errorStatus;
}
Run Code Online (Sandbox Code Playgroud)