gpt4 book ai didi

powershell httpwebrequest GET方法cookiecontainer有问题吗?

转载 作者:行者123 更新时间:2023-12-03 07:59:59 26 4
gpt4 key购买 nike

我正在尝试抓取具有用户身份验证的网站。我能够执行POST来发送登录信息并存储Cookie。但是,登录后,尝试访问 protected 页面时出现403错误。

$url = "https://some_url"

$CookieContainer = New-Object System.Net.CookieContainer

$postData = "User=UserName&Password=Pass"

$buffer = [text.encoding]::ascii.getbytes($postData)

[net.httpWebRequest] $req = [net.webRequest]::create($url)
$req.method = "POST"
$req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
$req.Headers.Add("Accept-Language: en-US")
$req.Headers.Add("Accept-Encoding: gzip,deflate")
$req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
$req.AllowAutoRedirect = $false
$req.ContentType = "application/x-www-form-urlencoded"
$req.ContentLength = $buffer.length
$req.TimeOut = 50000
$req.KeepAlive = $true
$req.Headers.Add("Keep-Alive: 300");
$req.CookieContainer = $CookieContainer
$reqst = $req.getRequestStream()
$reqst.write($buffer, 0, $buffer.length)
$reqst.flush()
$reqst.close()
[net.httpWebResponse] $res = $req.getResponse()
$resst = $res.getResponseStream()
$sr = new-object IO.StreamReader($resst)
$result = $sr.ReadToEnd()
$res.close()



$url2 = "https://some_url/protected_page"

[net.httpWebRequest] $req2 = [net.webRequest]::create($url2)
$req2.Method = "GET"
$req2.Accept = "text/html"
$req2.AllowAutoRedirect = $false
$req2.CookieContainer = $CookieContainer
$req2.TimeOut = 50000
[net.httpWebResponse] $res2 = $req2.getResponse()
$resst = $res2.getResponseStream()
$sr = new-object IO.StreamReader($resst)
$result = $sr.ReadToEnd()

变通方法:因此,在尝试了几乎所有方法之后,我最终尝试了一些不同的方法,并且它确实可行。

发布登录信息并获取 session cookie之后,我使用webclient通过将cookie字符串添加到标题中来访问安全页面。
$web = new-object net.webclient
$web.Headers.add("Cookie", $res.Headers["Set-Cookie"])
$result = $web.DownloadString("https://secure_url")

一件很酷的事情是,webclient保存了cookie。要访问另一个安全页面,您只需调用$ web.downloadstring(“https://another_secure_url”):)

最佳答案

我发现,由于cookie可以附加其他信息(例如URL或仅HTTP),因此$ res.Headers [“Set-Cookie”]对我不起作用。但是,使用$ CookieContainer变量,您可以轻松地将其更改为使用GetCookieHeader(url),它将删除多余的信息,并为您提供格式正确的cookie字符串:

$web = new-object net.webclient
$web.Headers.add("Cookie", $CookieContainer.GetCookieHeader($url))
$result = $web.DownloadString($url)

关于powershell httpwebrequest GET方法cookiecontainer有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5470474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com