简体   繁体   中英

Powershell how to get the result code from REST

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"

Following your input:

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

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

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

$apiReturn can then be used as response.

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')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM