1
votes

I'm trying to send to an Azure WebHook a Body who contain both headers+Body with a WebRequest :

$Body = @"
{
    "headers":
    {
        "ocp-apim-subscription-key":"xxxxxx",
        "ocp-apim-trace":"true"
    },
    "Body":
    {
        "toto": "xxxxxx-1505-xxxxx-8113-xxxxxxxxxx",
        "status": "Enable",
    }
}"@

I'm using:

Invoke-RestMethod -Uri $webhook_url -Headers $webhook_headers -Method $webhook_method -Body $Body

Everything is working, after that in Azure, I receive the Params Input with this:

workflow TestAPI
{
Param ([object]$WebHookData)
    if ($WebHookData)
    {
           # Get Webhook data
        $WebhookName = $WebHookData.WebhookName
        $WebhookHeaders = $WebHookData.RequestHeader
        $WebhookBody = $WebHookData.RequestBody

           # Body converting
        $body = (ConvertFrom-Json -InputObject $WebhookBody)

In the end of my script, I convert it again to Json and use the Invoke-Webrequest:

    $body_json = (Convertto-Json -InputObject $body.body -Depth 10)
    $header_json = (Convertto-Json -InputObject $body.headers -Depth 10 )
$response = Invoke-RestMethod -Uri $URI_key -Method $Method -Body $body_json -Headers $header_json -ContentType "application/json" -UseBasicParsing

But I get this error:

Invoke-RestMethod : Cannot bind parameter 'Headers'. Cannot convert the "{ "ocp-apim-subscription-key": "xxxxxxxxxxx", "ocp-apim-trace": "true" }" value of type "System.String" to type "System.Collections.IDictionary".

This is the output of the value $body.headers in PsObject after ConvertFrom-Json:

@{ocp-apim-subscription-key=xxxxxxxxx; ocp-apim-trace=true}

Output of $header_json after ConvertTo-Json:

{
    "ocp-apim-subscription-key":  "xxxxxxxxxxxxx",
    "ocp-apim-trace":  "true"
}
2

2 Answers

0
votes

The -Headers parameter requires a IDictionary object, a json string will not work.

You'll have to create a IDictionary object yourself since ConvertFrom-Json will de-serialize the json into a PSCutomObject.

You can do that like so:

$headers = @{}
($body | ConvertFrom-Json).Headers.PSObject.Properties | ForEach-Object { $headers[$_.Name] = $_.Value }

Now you can use the $headers variable with Invoke-RestMethod. That will fix the error you are receiving.

1
votes

To add on to Persistent13's commen, you can use something as simple as this, with PowerShell:

$headers = @{
    "Accept-Encoding" = 'gzip'
    "User-Agent"      = 'Outlook-Android'      
}
Invoke-WebRequest http://fq.dn -Headers $headers