2014-04-07 110 views
7

在Windows PowerShell 3.0中引入了Invoke-RestMethod cmdlet。PowerShell WebRequest POST

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方法(類似於Invoke-RestMethod中的Body參數)發送請求正文的能力,從而擴展此代碼示例?

回答

15

首先,更改更新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問題跟蹤器上報告,以便它們可以跟蹤和修復。

+1

謝謝,Trevor!這是我認爲應該實施的方式,但不知道這是最好的方式 –

+0

不客氣,@VadimGremyachev :)很高興這有助於你! –

+0

@TrevorSullivan如果我有一個JSON的話,身體會是什麼樣子? – Campinho

3
$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; 
}