【发布时间】:2017-07-10 19:29:03
【问题描述】:
我目前正在使用 powershell 自动执行 REST 调用。我有一个 REST API,我正在使用我的 Powershell 脚本和 Invoke-WebRequest 调用它,如下所示。
用于登录:-
Invoke-WebRequest -Method Post -uri $loginUri -ContentType application/x-www-form-urlencoded -Body $loginBody -Headers @{"Accept" = "application/xml"} -SessionVariable CookieSession -UseBasicParsing
在上面的 URL 类似于 Server/_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 是 Server/_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
}
}
【问题讨论】:
标签: .net powershell cookies powershell-2.0