ChatGPT解决这个技术问题 Extra ChatGPT

Invoke-WebRequest, POST 带参数

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

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

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

有关类似问题,请参见 this answer
您也可以考虑this Q/A or the referenced answer

J
Jellezilla

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

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

对于我未来的参考和其他人的信息一样,哈希表也可以单行样式直接传递给 -Body 参数。
添加 $ProgressPreference = 'SilentlyContinue' 以将速度提高 10 倍。
在转到 json 版本之前,我会先尝试这个 non-json hash-table 解决方案,请参阅@rob。
只是多了一些内容。感谢 Timo,link to rob's answer。像cori 建议的oneliner 将是Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body @{username='me';moredata='qwerty'}(可能带有$ProgressPreference = 'SilentlyContinue')。请注意,与 curl 相比,变量名称没有引号 "= 代替 :; 代替 ,
-UseDefaultCredentials 传入 Windows 身份验证用户
r
rob

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

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

或 XML 等的等价物。


F
Francesco Mantovani

这很有效:

$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?或者这是可选的?
@Cadoiz,与其他标题一样,它是可选的。取决于您使用的服务,如果它关心这些值。
G
GorvGoyl

使用 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

查看更多:Power up your PowerShell


注意力!与 curl 相比,您有 = 而不是 :。您在代码块中做得正确,但可能不在上面。 ; 而不是 , 是正确的,变量名称的引号 " 没问题,只是 PowerShell 不需要。