Invoke-WebRequest,带有参数的POST


197

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

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

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


2
看到类似问题的答案
Ansgar Wiechers 2013年

Answers:


300

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

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

8
对于我以后的参考以及其他任何人的信息,也可以将单表样式的哈希表直接传递给-Body参数。
cori

2
加$ ProgressPreference =“SilentlyContinue”为了加快速度通过的10倍。
安德烈

93

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

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

或等效的XML等。


15

这只是工作:

$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

3

用作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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.