2017-02-21 40 views
1

我目前正在使用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 
     } 

} 

回答

1

所以做了很多的调查后,我发现了一条出路。

我遇到的问题是cookie容器在我的调用之间迷路了。在.NET cookie的容器储存在$的CookieContainer

我所要做的就是在创建cookie的容器,我不得不让全球

$global:CookieContainer = New-Object System.Net.CookieContainer 

然后在我的第一个电话是登录,指定为相同的cookie容器

$req.CookieContainer = $CookieContainer 

所以,登录,当同样是成功的过程中,你的变量$的CookieContainer存储的价值和所有的休息以下电话具有相同的cookie容器

$ req.CookieContainer = $的CookieContainer

你可以简单地继续使用这个直到你关闭你的会话。

+0

这是相当不错的方式。对答案进行一点修改,保持上下文相同。 –