我正在运行一个 PowerShell 脚本,该脚本通过 HTTPS 将数据发布到内部 Web 服务器。SSL 证书无效。我正在使用
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
接受证书,当从命令行运行脚本时它可以工作,但我收到错误
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
作为计划任务运行时。具体命令是
Invoke-WebRequest -Uri 'https://host/login.cgi' -Method POST -Body 'username&password' -UseBasicParsing
答案1
最后,我只是恢复了更基本的.NET 功能:
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
[System.Net.ServicePointManager]::Expect100Continue = $false
$cookies = New-Object System.Net.CookieContainer
$request = [System.Net.HttpWebRequest]::Create('https://host')
$request.Method = 'POST'
$request.CookieContainer = $cookies
$postData = 'stringdata'
$data = [System.Text.Encoding]::ASCII.GetBytes($postData)
$request.ContentLength = $data.Length
$requestStream = $request.GetRequestStream()
$requestStream.Write($data, 0, $data.Length)
$requestStream.Close()
$response = [System.Net.HttpWebResponse]$request.GetResponse()
$responseStream = $response.GetResponseStream()
(New-Object System.IO.StreamReader($responseStream)).ReadToEnd()