Powershell如何从REST获取结果代码 [英] Powershell how to get the result code from REST

查看:38
本文介绍了Powershell如何从REST获取结果代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发送一个带有 ID/密码的 POST 请求,我需要取回一个响应令牌,我该如何获取并保存它以供以后在脚本中使用?

I'm sending a POST request with ID/password and I need to get back a respond token, how can I get it and save it for later use in the script?

$loginUrl = "https://some-ip"

$params = @{
 "username"="$username"
 "password"="$password"
}

Invoke-WebRequest -Uri $loginUrl -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

推荐答案

按照您的输入:

$url = "https://some-ip"

$params = @{
 "username" = $username
 "password" = $password
} | ConvertTo-Json

$apiReturn = Invoke-RestMethod -Uri $url -Method POST -Body $params -ContentType "application/json"

$apiReturn 然后可以用作响应.

此外,您可以使用Invoke-RestMethodSessionVariable参数.

Furthermore, you can use the SessionVariable parameter of Invoke-RestMethod.

$apiReturn = Invoke-RestMethod -Uri $url -Method POST -Body $params -ContentType "application/json" -SessionVariable sessionToken
$sessionToken.Headers.Add('Authorization', $apiReturn)
$sessionToken.Headers.Add('Content-Type', 'application/json')

在这种情况下,您将响应令牌添加到授权"并将整个令牌转发到您后续的 API 调用.像这样你只需要添加 $sessionTokenContent-Type 例如已经提供.

In this scenario, you add the response token to 'Authorization' and forward the whole token to your subsequent API calls. Like this you only need to add $sessionToken and Content-Type for example is already provided.

Invoke-RestMethod -Method Post -Uri $url -WebSession $sessionToken 

如果需要,您可以在标题中添加更多参数.

You can add more parameters to your Header in case it is required.

这篇关于Powershell如何从REST获取结果代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆