使用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}
谁能提供一些指导,说明这里可能出了什么问题以及如何修复它?
谢谢
发布于 2013-04-06 03:20:05
基本上,在您的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"
发布于 2017-09-16 21:43:26
Lee的回答很好,但我也有关于web服务器支持的协议的问题。
在添加了以下几行之后,我可以获得https请求。正如在这个答案中指出的https://stackoverflow.com/a/36266735
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
我使用Lee的代码的完整解决方案。
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;
}
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
发布于 2019-03-20 00:59:52
纯powershell的替代实现(没有c#源代码的Add-Type
):
#requires -Version 5
#requires -PSEdition Desktop
class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
[bool] CheckValidationResult([System.Net.ServicePoint] $a,
[System.Security.Cryptography.X509Certificates.X509Certificate] $b,
[System.Net.WebRequest] $c,
[int] $d) {
return $true
}
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()
https://stackoverflow.com/questions/11696944
复制相似问题