PowerShell POST Request

In Windows PowerShell 3.0, the Invoke-RestMethod cmdlet was introduced.

Invoke-RestMethod cmdlet accepts the -Body<Object> parameter to set the request body.

Due to some limitations of Invoke-RestMethod, the cmdlet cannot be used in our case. On the other hand, the alternative solution described in the InvokeRestMethod article for other users meets our needs:

 $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 

But it is intended only for the GET method. Could you suggest how to extend this sample code with the ability to send the request body using the POST method (similar to the Body parameter in Invoke-RestMethod )?

+7
powershell
source share
2 answers

First, change the line that updates the HTTP method.

 $request.Method= 'POST'; 

Then you need to add the message body to the HttpWebRequest object. To do this, you need to get a link to the request stream, and then add data to it.

 $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(); 

NOTE : The PowerShell Core version is now open source on GitHub and the cross-platform platform of Linux, Mac, and Windows. Any problems with the Invoke-RestMethod should be sent to the GitHub tracker for this project, so they can be tracked and fixed.

+15
source share
 $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; } 
+3
source share

All Articles