PowerShell和cURL-获取JSON响应并检查HTTP响应代码

时间:2018-12-09 12:27:15

标签: powershell curl

我有以下PowerShell脚本:

$CURLEXE = 'C:\Windows\System32\curl.exe'
$URL1 = "Example.com"

$GetTokenCurl = '-s', '-v', '-X', 'POST',
    $URL1,
    '-H', 'Content-Type: application/x-www-form-urlencoded',
    '-d', 'grant_type=client_credentials&client_id=12345678&client_secret=abcdefgh',
    '--retry', '2', 
    '--retry-connrefused',
    '--retry-delay', '3'

Write-Host "Command took" (Measure-Command {$GetTokenResponse = & $CURLEXE @GetTokenCurl}).TotalSeconds "Seconds"

$GetTokenJSON = ConvertFrom-Json -InputObject $GetTokenResponse -ErrorAction SilentlyContinue

$SessionToken = $GetTokenJSON.access_token
$AuthBearer = "Authorization: Bearer " + $SessionToken

它从SSO服务器获取我的访问令牌,并将其存储到$ AuthBearer变量中,这样我就可以将其重用于以后的脚本中。

我的回复看起来像这样:

{"access_token":"987654321","token_type":"Bearer","expires_in":3600}

我还尝试验证服务器的HTTP响应代码,到目前为止,我只能通过启用-v(详细)输出来执行此操作。我正在特别寻找< HTTP/1.1之后的HTTP响应代码(即 200 )。我可以在详细输出中看到这一点:

< HTTP/1.1 200 OK

我终生无法找到将JSON响应存储在变量中并检查Verbose输出内容的方法。

我尝试将Verbose输出写入文本文件失败。 我尝试了以下两个开关,但这些开关弄乱了我的JSON响应:

-i, --include       Include protocol response headers in the output
-I, --head          Show document info only

我还尝试了--output到文件,但这只是写了我的JSON响应,而不是对文件的详细响应:

--output <file> Write to file instead of stdout

是否可以使用PowerShell和cURL来获取JSON响应检查HTTP响应代码?

0 个答案:

没有答案