[Solved] Invoke-WebRequest, POST with parameters

I’m attempting to POST to a uri, and send the parameter username=me

Invoke-WebRequest -Uri http://example.com/foobar -Method POST

How do I pass the parameters using the method POST?

Enquirer: kylex


Solution #1:

Put your parameters in a hash table and pass them like this:

$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams
Respondent: Jellezilla

Solution #2:

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

Respondent: rob

Solution #3:

This just works:

$body = @{
 "OptionalEmail"="[email protected]"
} | ConvertTo-Json

$header = @{

Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML

Solution #4:

Single command without ps variables when using JSON as body {lastName:"doe"} for POST api call:

Invoke-WebRequest -Headers @{"Authorization" = "Bearer N-1234ulmMGhsDsCAEAzmo1tChSsq323sIkk4Zq9"} `
                  -Method POST `
                  -Body (@{"lastName"="doe";}|ConvertTo-Json) `
                  -Uri https://api.dummy.com/getUsers `
                  -ContentType application/json
Respondent: GorvGoyl

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.