Invoke-WebRequest,带参数的POST

kyl*_*lex 177 powershell

我正在尝试POST到uri,并发送参数 username=me

Invoke-WebRequest -Uri http://example.com/foobar -Method POST
Run Code Online (Sandbox Code Playgroud)

如何使用POST方法传递参数?

Jel*_*lla 270

将您的参数放在哈希表中并像这样传递它们:

$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams
Run Code Online (Sandbox Code Playgroud)

  • 对于我将来的参考和其他任何人的信息一样,哈希表也可以直接传递给-Body参数,单行样式. (7认同)
  • 添加 $ProgressPreference = 'SilentlyContinue' 将速度提高 10 倍。 (3认同)

rob*_*rob 84

对于某些挑剔的Web服务,请求需要将内容类型设置为JSON,将主体设置为JSON字符串.例如:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"
Run Code Online (Sandbox Code Playgroud)

或等效的XML等


Jer*_*yal 10

用作 POST api 调用的JSON正文时,没有 ps 变量的单个命令{lastName:"doe"}

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

  • 注意力!与curl 相比,你有`=` 而不是`:`。您在代码块中的做法是正确的,但在上面可能不是。`;` 而不是 `,` 是正确的,变量名称的引号 `"` 也可以,只是 PowerShell 不需要。 (2认同)

Fra*_*ani 7

这只是工作:

$body = @{
 "UserSessionId"="12345678"
 "OptionalEmail"="MyEmail@gmail.com"
} | ConvertTo-Json

$header = @{
 "Accept"="application/json"
 "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
 "Content-Type"="application/json"
} 

Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
Run Code Online (Sandbox Code Playgroud)