gpt4 book ai didi

powershell - 如何在Powershell中转义Invoke-Webrequest

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

我有一个带有状态页面的网络设备,该页面可以通过Java小程序访问。使用Fiddler,我可以找到状态的http提要,但是页面会不断刷新。 (Firefox会显示该页面,但会保持刷新状态,Chrome会将其视为无扩展名的文件,并尝试保存它,但由于总有更多数据,因此无法完成。)

状态页面使用NTLM身份验证,因此尽管我将使用Invoke-Webrequest。以下代码登录并开始下载页面,但是由于其恒定的数据流永远无法完成:

$url = "http://xxx.xxx.xxx.xxx/api/notify"
$user = "user"
$pass= "password"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$data = Invoke-restmethod $url -Credential $credential

收到一定数量的字符后,是否有办法从Invoke-Webrequest中逃脱?还是有更好的方法来做到这一点?

最佳答案

我认为Invoke-WebRequest不可行,但是您可以改用.NET WebRequestStreamReader类。例:

$sUri = "http://www.w3.org" # Replace with your URI
$sEncoding = "utf-8"
$iCharactersToRead = 1000 # How many characters we want to read
$sAuthType = "NTLM"
$sUserName = "username"
$sPassword = "password"

# Creating a new HttpWebRequest object.
[System.Net.HttpWebRequest]$oHttpWebRequest = [System.Net.WebRequest]::Create($sUri)
# This may be superflous if your HTTP server doesn't use compression.
$oHttpWebRequest.AutomaticDecompression = `
([System.Net.DecompressionMethods]::Deflate `
-bor [System.Net.DecompressionMethods]::GZip)

# Since you have NTLM auth, you need to add a credential.
$oCredential = New-Object -TypeName System.Net.NetworkCredential($sUserName, $sPassword)
$oCredentialCache = New-Object -TypeName System.Net.CredentialCache
$oCredentialCache.Add($sUri, "NTLM", $oCredential)
$oHttpWebRequest.Credentials = $oCredentialCache

# Creating a StreamReader object that will read the response stream.
$oResponseStream = $oHttpWebRequest.GetResponse().GetResponseStream()
$oContentReader = New-Object -TypeName System.IO.StreamReader($oResponseStream,
[System.Text.Encoding]::GetEncoding($sEncoding), $true)

# Trying to read the specified number of characters from the stream.
$sContent = [String]::Empty
try {
for ($i = 0; $i -lt $iCharactersToRead; $i++) {
$sContent += [Char]$oContentReader.Read()
}
}
finally {
$oContentReader.Close()
}

代替 utf-8,您可能需要指定其他编码名称,具体取决于HTTP服务器使用的编码。有关更多详细信息,请参见 Encoding.WebName引用。

关于powershell - 如何在Powershell中转义Invoke-Webrequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31794551/

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