15

How would I use Invoke-WebRequest to post all these parameters

POST /token HTTP/1.1
Host: login.huddle.net
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&client_id=s6BhdRkqt&redirect_uri=MyAppServer.com/receiveAuthCode&code=i1WsRn1uB

2 Answers 2

39

Here's how to convert that body into one which PowerShell can interpret.

$body = @{grant_type='authorization_code'
      client_id='s6BhdRkqt'
      redirect_uri='MyAppServer.com/receiveAuthCode'
      code='i1WsRn1uB'}
$contentType = 'application/x-www-form-urlencoded' 
Invoke-WebRequest -Method POST -Uri yourUrl -body $body -ContentType $contentType
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Thats exactly what I was doing but havent achieved what I am looking for. Could you please look this post. Havent got any answer to it. Its just I dont see the access token in response. Thanks again stackoverflow.com/questions/41707868/…
Added a comment to that post but the TLDR is that you should use Invoke-RestMethod instead of Invoke-WebRequest. With all the same params it should Just work.
Thank you, i was using [PSCustomObject]@{name='bla'}, and this content type does not like a body that is a PSCustomObject!
Understandable, @Omzig, as PowerShell muscle memory kind of trains us to always prefix a hashtable with [psCustomObject]. However the Invoke-WebRequest cmdlets rely on us, the authors, to convert our -Body value to the right content type. In the modern Web that is almost always JSON for most APIs, but sometimes not. Contrast that with Invoke-Restmethod, which assumes you're working with Rest and so always converts the body value into JSON.
2

Do something like that

$loginPage = Invoke-WebRequest "http:\\website.com\" # invoke login form page
$loginForm = $loginPage.Forms[0] # Get the form to fill
$loginForm.fields["userName"] = "usrnm" # fill the username
$loginForm.fields["password"] = "psswd" # fill the password
$loginPage = Invoke-WebRequest -Uri ("http:\\website.com\") -Method POST -Body $loginForm.fields # Post the form to log-in

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.