这里是Powershell的新手,所以如果有任何建议,我们将不胜感激!我张贴到这个网站的应用程序接口(在下面的代码中我将其代号为authenticate.com ),以在响应中接收作为cookie的身份验证令牌。下一个目标是获取cookie并使用它对不同的API进行验证。如何捕获第一个API返回的auth-token并将其保存到变量中?
我的代码:
$Url = 'https://authenticate.com/apikeylogin'
$auth = @{
keyPublic= '********************'
keySecret= '********************'
}
$json = $auth | ConvertTo-Json
$response = Invoke-WebRequest $Url -Method Post -Body $json -ContentType 'application/json'
$response | Get-Member
$response.RawContent原始文本形式的响应:
HTTP/1.1 200 OK
auth-token: ******************
[Below this is are a dozen more lines of raw data]为了重申这个问题,我如何获得'auth-token‘的上述值并将其存储到一个变量中?
发布于 2020-06-16 03:11:16
好了,我已经用.Substring()解决了这个问题。
$auth = @{
keyPublic= '********************'
keySecret= '********************'
}
$json = $auth | ConvertTo-Json
$response = Invoke-WebRequest $Url -Method Post -Body $json -ContentType 'application/json'
$raw = $response.RawContent
$string = $raw | Out-String
$auth_token = $string.Substring(35, 90)我从API请求的访问令牌始终具有相同的长度,因此我使用substring方法来准确地确定字符串中的哪些字符是我需要的,然后将它们存储在变量"auth- token“中
发布于 2020-06-15 14:57:43
您可以使用Select-String (类似于powershell中的grep )找出包含auth-token的行,并获得auth-tok值。
$response = "HTTP/1.1 200 OK `
auth-token: ABCDEFGHIJKLMNOP `
[Below this is are a dozen more lines of raw data]"
$authTokenline =
$response.Split("`n") | Select-String -Pattern "^auth-token:.*$"
$authToken = $authTokenline.ToString().Split(":")[1]ABCDEFGHIJKLMNOPhttps://stackoverflow.com/questions/62379770
复制相似问题