You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PowerShell中Invoke-RestMethod的SSL/TLS连接及语法问题求助

解决PowerShell中Invoke-RestMethod的语法错误与SSL/TLS连接问题

我来帮你一步步搞定这两个问题——先修正语法错误,再处理SSL/TLS的连接问题:

一、先修复代码里的语法错误

你的原始代码有几处语法问题,我给你标出来并修正:

  • 字符串类型的变量(比如$loginurl$method)必须用引号包裹,PowerShell才会识别为字符串
  • Invoke-RestMethod返回的是解析后的响应对象,没有RawContent属性;如果需要获取原始响应内容,应该用Invoke-WebRequest

修正后的基础代码如下:

$loginurl = "https://education.org/logon"
$data = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$data.Add('username','abc')
$data.Add('password','abc')
$method = "POST"
# 如果需要原始响应内容,用Invoke-WebRequest
$response = Invoke-WebRequest -Method $method -Uri $loginurl -Body $data
$response.RawContent

# 如果只需要解析后的响应数据,用Invoke-RestMethod
# $response = Invoke-RestMethod -Method $method -Uri $loginurl -Body $data
# $response

二、处理SSL/TLS连接错误(对应curl的--insecure参数)

curl的--insecure参数是用来跳过SSL证书验证的,在PowerShell里可以通过两种方式实现:

方法1:启用更兼容的SSL/TLS协议版本

有些网站可能只支持旧版的TLS协议,而PowerShell默认的协议可能不兼容,你可以先设置允许使用TLS 1.2/1.3:

# 设置支持TLS 1.2和1.3
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13

方法2:跳过SSL证书验证(完全对应--insecure)

如果网站的证书本身无效(比如自签名证书),可以通过自定义证书回调来跳过验证,但注意:这会带来安全风险,仅在测试或信任的环境中使用

# 创建跳过证书验证的回调
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

整合后的完整代码

把上面的设置和修正后的请求代码结合起来,就是能正常运行的版本:

# 先处理SSL/TLS相关设置
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13
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

# 执行请求
$loginurl = "https://education.org/logon"
$data = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$data.Add('username','abc')
$data.Add('password','abc')
$method = "POST"
$response = Invoke-WebRequest -Method $method -Uri $loginurl -Body $data
$response.RawContent

内容的提问来源于stack exchange,提问作者Vivek Sharma

火山引擎 最新活动