我目前正在使用PowerShell自动执行REST调用。我有一个REST API,我用下面的Invoke-WebRequest与我的powershell脚本调用。PowerShell版本2中的会话变量--net.httpWebRequest
对于日志: -
Invoke-WebRequest -Method Post -uri $loginUri -ContentType application/x-www-form-urlencoded -Body $loginBody -Headers @{"Accept" = "application/xml"}
-SessionVariable CookieSession -UseBasicParsing
在以上网址是像服务器/ _login和身体,我的凭据作为
传递$loginBody = "username=$username&password=$password"
我从这个调用中获取cookie(JSESSIONID),然后解析其他所有调用。例如
我的退出是这样的: -
Invoke-WebRequest -Method Post -uri $logOutUri -ContentType application/xml -Headers @{"Accept" = "application/xml"}
-WebSession $ SessionVariable -UseBasicParsing
其中URL是服务器/ _Logout和使用-WebSession我解析cookie的
问题是,我必须使其与PowerShell版本2兼容,因此必须使用[System.Net.HttpWebRequest]
所以我需要一个函数来第一次登录这将返回我的sessioncookie,然后我必须解析所有其他调用该cookie。
下面是我开始的,但不知道什么进一步: -
function Http-Web-Request([string]$method,[string]$Accept,[string]$contentType, [string]$path,[string]$post)
{
$url = "$global:restUri/$path"
$CookieContainer = New-Object System.Net.CookieContainer
$postData = $post
$buffer = [text.encoding]::ascii.getbytes($postData)
[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest] [System.Net.WebRequest]::Create($url)
$req.method = "$method"
$req.Accept = "$Accept"
$req.AllowAutoRedirect = $false
$req.ContentType = "$contentType"
$req.ContentLength = $buffer.length
$req.CookieContainer = $CookieContainer
$req.TimeOut = 50000
$req.KeepAlive = $true
$req.Headers.Add("Keep-Alive: 300");
$reqst = $req.getRequestStream()
$reqst.write($buffer, 0, $buffer.length)
try
{
[System.Net.HttpWebResponse] $response = $req.GetResponse()
$sr = New-Object System.IO.StreamReader($response.GetResponseStream())
$txt = $sr.ReadToEnd()
if ($response.ContentType.StartsWith("text/xml"))
{
## NOTE: comment out the next line if you don't want this function to print to the terminal
Format-XML($txt)
}
return $txt
}
catch [Net.WebException]
{
[System.Net.HttpWebResponse] $resp = [System.Net.HttpWebResponse] $_.Exception.Response
## Return the error to the caller
Throw $resp.StatusDescription
}
}
这是相当不错的方式。对答案进行一点修改,保持上下文相同。 –