I am currently working on automating a REST call with powershell. I have a REST API which i was calling with my powershell script with Invoke-WebRequest as below.
For logging in:-
Invoke-WebRequest -Method Post -uri $loginUri -ContentType application/x-www-form-urlencoded -Body $loginBody -Headers @{"Accept" = "application/xml"} -SessionVariable CookieSession -UseBasicParsing
In the above the URL is something like Server/_Login and in the body, my credentials are passed as
$loginBody = "username=$username&password=$password"
I was getting the cookie (JSESSIONID) from this call and then parse the same to all other calls. For example
My Logout looks like this:-
Invoke-WebRequest -Method Post -uri $logOutUri -ContentType application/xml -Headers @{"Accept" = "application/xml"} -WebSession $SessionVariable -UseBasicParsing
where urL is Server/_Logout and using -WebSession i am parsing the cookie
The problem is, i have to make this compatible with powershell version 2 and hence has to use [System.Net.HttpWebRequest]
So i need a function to first login which will return me the sessioncookie and then i have to parse that cookie for all other calls.
Below is what i started with but dont know what further:-
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
}
}