Home > Net >  Powershell Invoke-RestMethod with body begins from array
Powershell Invoke-RestMethod with body begins from array

Time:07-07

I have a web server that responds to a request https://localhost/GetUpdateInfo with a body [{"ipAddress": "10.200.2.55"}] In postman its Work but in powershell i can`t do this because body begins from array.

When i do exmple code:

$Url = "https://localhost/GetUpdateInfo"
$Body = @(@{
    ipAddress = "10.200.2.55"
    })
      $jsonBody = ConvertTo-Json -InputObject $Body
Invoke-RestMethod -Method 'Post' -Uri $url  -Body $jsonBody 

i hve error: Invoke-RestMethod : Block length does not match with its complement.

CodePudding user response:

The content type of all POST requests is application/x-www-form-urlencoded unless specified.

Add -ContentType application/json to your last line call so your json is sent correctly.

Invoke-RestMethod -Method 'Post' -Uri $url  -Body $jsonBody -ContentType 'application/json'

CodePudding user response:

Looks like the problem is that your array only has one element and PowerShell 'unrolls' that, losing the surrounding array.

If you do:

$Body = @(@{
    ipAddress = "10.200.2.55"
})

the resulting json will be:

{
    "ipAddress":  "10.200.2.55"
}

You can make it into an array by manually adding the [ and ] like this:

$jsonBody = '[{0}]' -f ($Body | ConvertTo-Json -Compress)

Which yields [{"ipAddress":"10.200.2.55"}] and then send that using

Invoke-RestMethod -Method 'Post' -Uri $url -Body $jsonBody -ContentType 'application/json'
  • Related