如何使用Invoke-WebRequest发送请求

13

我该如何使用Invoke-WebRequest来提交所有这些参数?

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个回答

32

这里是如何将该正文转换为 PowerShell 可以解释的内容。

$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 <i>yourUrl</i> -body $body -ContentType $contentType

谢谢。那正是我正在做的事情,但我还没有达到我要找的东西。你能看一下这篇文章吗?我还没有得到任何答案。我只是没有在响应中看到访问令牌。再次感谢。http://stackoverflow.com/questions/41707868/need-to-get-required-http-post/41707939#41707939 - Zz11
在那篇帖子中添加了一条评论,但简而言之,你应该使用Invoke-RestMethod而不是Invoke-WebRequest。使用相同的参数,它应该“只是工作”。 - FoxDeploy
1
谢谢,我之前在使用[PSCustomObject]@{name='bla'}时,发现这种内容类型不支持作为请求主体! - Omzig
2
可以理解,@Omzig,因为PowerShell的肌肉记忆让我们总是在哈希表前加上[psCustomObject]。然而,Invoke-WebRequest cmdlet依赖于我们这些作者将我们的-Body值转换为正确的内容类型。在现代Web中,对于大多数API来说,这几乎总是JSON,但有时不是。与此形成对比的是Invoke-Restmethod,它假设您正在使用Rest,因此始终将body值转换为JSON。 - FoxDeploy

2

做类似于这样的事情

$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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接