我试图POST到一个uri,并发送参数username=me

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

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


当前回答

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

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

或者等价的XML等等。

其他回答

把你的参数放到哈希表中,然后像这样传递:

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

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

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

或者等价的XML等等。

这是可行的:

$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

当使用JSON作为body {lastName:"doe"}进行POST api调用时,单个命令不带ps变量:

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

查看更多:启动您的PowerShell