La seguente funzione
InvokeJsonRequest usa il metodo
Invoke-RestMethod di
PowerShell per invocare una chiamata ad un servizio
REST con content type
application/json:
function InvokeJsonRequest {
param (
[string]$url,
[boolean]$post = $false,
$object = $null
)
$result = $null
# header per content type JSON
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json")
if($post -eq $true){
# in caso di POST
$dataJson = $object | ConvertTo-Json -Depth 4
$result = Invoke-RestMethod -Method 'POST' -Uri $url -UseDefaultCredentials -Body $dataJson -Headers $headers
} else {
# in caso di GET
$result = Invoke-RestMethod -Method 'GET' -Uri $url -UseDefaultCredentials -Headers $headers
}
$result
}
da usare in caso di
GET come:
$result = InvokeJsonRequest "https://localhost/api/test?param=1"
oppure in caso di
POST:
$data = @{
ID = 1;
Email = "farlocca@farlocchi.it"
};
$result = InvokeJsonRequest "https://localhost/api/testPost" $true $data