如果正文参数以“@”开头,则发出 PowerShell POST 请求

Making a PowerShell POST request if a body param starts with '@'

我想在 PowerShell 中发出 POST 请求。以下是 Postman 中的 body 详细信息。

{
  "@type":"login",
  "username":"xxx@gmail.com",
  "password":"yyy"
}

如何在 PowerShell 中传递它?

您应该能够做到以下几点:

$params = @{"@type"="login";
 "username"="xxx@gmail.com";
 "password"="yyy";
}

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params

这会将 post 作为正文发送。但是 - 如果你想 post this as a Json 你可能想要明确。要将此 post 作为 JSON,您可以指定 ContentType 并使用

将正文转换为 Json
Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

额外: 您还可以使用 Invoke-RestMethod 来处理 JSON 和 REST api(这将为您节省一些额外的反序列化行)

使用 Invoke-RestMethod 使用 REST-API。将 JSON 保存为字符串并将其用作正文,例如:

$JSON = @'
{"@type":"login",
 "username":"xxx@gmail.com",
 "password":"yyy"
}
'@

$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

如果您使用 Powershell 3,我知道 Invoke-RestMethod 存在一些问题,但您应该可以使用 Invoke-WebRequest 作为替代:

$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

如果你不想每次都写自己的JSON,你可以使用哈希表并使用PowerShell将其转换为JSON后再发布。例如

$JSON = @{
    "@type" = "login"
    "username" = "xxx@gmail.com"
    "password" = "yyy"
} | ConvertTo-Json

@Frode F. 给出了正确答案

顺便说一句 Invoke-WebRequest 也给你打印了 200 OK 和很多 bla, bla, bla... 这可能有用,但我仍然更喜欢 Invoke-RestMethod 这是打火机。

此外,请记住您只需要为 body 使用 | ConvertTo-Json,而不是 header:

$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

然后您可以在请求的末尾附加一个 | ConvertTo-HTML 以获得更好的可读性