MisterPuggles
MisterPuggles

Reputation: 143

Calling a URL via POST method with JSON object, but using Powershell

I am attempting to call a specific URL via POST method, where a JSON object is passed as a POST form parameter. The JSON object that needs to be passed is something like this:

obj={
"login":"[username here]",
"pword":"[password here]"
}

With Powershell, I was attempting to create a hash and then convert that into JSON, then connect with the Invoke-RestMethod command.

$hash = @{  login = "username"; 
            pword = "password"
            }

$obj = $hash | convertto-json
Invoke-RestMethod 'https://website.com/login' -Method POST -Body $obj -ContentType 'application/x-www-form-urlencoded'

However, this returns an error. Double-checking the documentation, it notes that the form parameter name MUST be obj, as the web services looks specifically for a parameter called obj, takes the string value, then converts it back to a JSON object to retrieve the internal values.

This is where I am getting a little stuck. How exactly can I specific a form parameter name when using Powershell?

Upvotes: 3

Views: 1448

Answers (1)

briantist
briantist

Reputation: 47772

The form you've presented:

obj={
"login":"[username here]",
"pword":"[password here]"
}

Appears to be invalid JSON. So.. you'd have to fudge it:

$hash = @{  login = "username"; 
            pword = "password"
            }

$obj = $hash | convertto-json
$obj = 'obj=' + $obj
Invoke-RestMethod 'https://website.com/login' -Method POST -Body $obj -ContentType 'application/x-www-form-urlencoded'

Upvotes: 2

Related Questions