2014-04-07 16 views
7

In Windows PowerShell 3.0 è stato introdotto il cmdlet Invoke-RestMethod.PowerShell WebRequest POST

Invoke-RestMethod Il cmdlet accetta il parametro -Body<Object> per l'impostazione del corpo della richiesta.

A causa di alcune limitazioni, nel nostro caso non è stato possibile utilizzare il cmdlet Invoke-RestMethod. Da altra parte, una soluzione alternativa descritta nell'articolo InvokeRestMethod for the Rest of Us adatta alle nostre esigenze:

$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 

tuttavia è destinato solo per un metodo GET. Potrebbe suggerire come estendere questo esempio di codice con la possibilità di inviare il corpo della richiesta utilizzando il metodo POST (simile al parametro Body in Invoke-RestMethod)?

risposta

15

Innanzitutto, modificare la linea che aggiorna il metodo HTTP.

$request.Method= 'POST'; 

Successivamente, è necessario aggiungere il corpo del messaggio con l'oggetto HttpWebRequest. Per fare ciò, è necessario prendere un riferimento al flusso di richiesta e quindi aggiungere dati ad esso.

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

NOTA: edizione PowerShell Core è ora open source su GitHub e multipiattaforma su Linux, Mac e Windows. Eventuali problemi con il cmdlet Invoke-RestMethod devono essere segnalati sul tracker dei problemi di GitHub per questo progetto, in modo che possano essere monitorati e risolti.

+1

grazie, Trevor! Questo è il modo in cui ho pensato che dovrebbe essere implementato, ma non ero sicuro che questo sia il modo migliore –

+0

Siete i benvenuti, @VadimGremyachev :) Sono contento che questo ti abbia aiutato! –

+0

@TrevorSullivan Come sarebbe il corpo se avessi un json su di esso? – 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; 
} 
Problemi correlati