使用 Powershell v3 的 Invoke-WebRequest 和 Invoke-RestMethod 我已经成功地使用 POST 方法将 json 文件发布到 https 网站。

我正在使用的命令是

 $cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("cert.crt")
 Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Body $json -ContentType application/json -Method POST

但是,当我尝试使用 GET 方法时:
 Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Method GET

返回以下错误
 Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
 At line:8 char:11
 + $output = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred
 +           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest)      [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

我尝试使用以下代码忽略 SSL 证书,但我不确定它是否真的在做任何事情。
 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

有人可以就此处可能出现的问题以及如何解决问题提供一些指导吗?

谢谢

最佳答案

这种解决方法对我有用:
http://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors

基本上,在您的 PowerShell 脚本中:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

关于.net - Powershell v3 Invoke-WebRequest HTTPS 错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11696944/

10-16 11:33
查看更多