我正在尝试调用设备上的 REST API,但它使用 https 套接字的自签名证书。我尝试在 PowerShell 中更改以下内容
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
但是在使用以下方式调用电话时,
$uri = 'https://hostname/api/config'
$headers = @{"Authorization"="token apitokengoeshere"}
try {
Invoke-RestMethod -Uri $uri -Headers $headers
}
catch {
$_.Exception |format-list -force
}
但我仍然收到以下错误
Status : SendFailure
Response :
Message : The underlying connection was closed: An unexpected
error occurred on a send.
Data : {}
InnerException : System.IO.IOException: Unable to read data from the
transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
TargetSite : System.Net.WebResponse
GetResponse(System.Net.WebRequest)
StackTrace : at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
HelpLink :
Source : Microsoft.PowerShell.Commands.Utility
HResult : -2146233079
我什至尝试安装 Tunable-SSL Powershell 模块,如博客中提到的 Here关于之前的问题。
最佳答案
我编写了一个简单的脚本,用于检查具有自签名证书的 HTTPS 页面上的结果代码状态。
通过大量谷歌搜索,这就是我最终得到的结果:
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;
}
}
"@ -ea SilentlyContinue -wa SilentlyContinue
然后在 Invoke-WebRequest 调用之前执行以下操作:
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
关于PowerShell 使用自签名证书连接到 REST API。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289236/