【发布时间】:2013-06-26 16:13:46
【问题描述】:
我正在尝试 POST 到 uri,并发送参数 username=me
Invoke-WebRequest -Uri http://example.com/foobar -Method POST
如何使用 POST 方法传递参数?
【问题讨论】:
-
查看this answer 类似的问题。
标签: powershell rest
我正在尝试 POST 到 uri,并发送参数 username=me
Invoke-WebRequest -Uri http://example.com/foobar -Method POST
如何使用 POST 方法传递参数?
【问题讨论】:
标签: powershell rest
将您的参数放入哈希表中并像这样传递它们:
$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams
【讨论】:
non-json hash-table 解决方案,然后再转到json版本,请参阅@rob。
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body @{username='me';moredata='qwerty'}(可能是$ProgressPreference = 'SilentlyContinue')。请注意,与 curl 相比,变量名称没有引号 " 和 = 而不是 : 和 ; 而不是 ,。
-UseDefaultCredentials 传入Windows认证用户
对于一些挑剔的 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
【讨论】:
connectapitoken?还是这是可选的?
单个命令在使用 JSON 作为主体 {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 不需要。