使用PowerShell Invoke-RestMethod调用SMS API遇验证错误求助
解决PowerShell Invoke-RestMethod发送短信返回Validation Error的问题
最可能的原因:布尔值类型不匹配
你在PowerShell里把twoway和checknumber设成了字符串"false"、"true",但Postman里发送的应该是原生布尔值(不带引号的false/true),服务端验证时会因为参数类型不符报错。
修改代码,把这两个参数换成PowerShell的原生布尔值:
$url = "https://1234.com/api/send" # 修正布尔值类型,去掉引号,用PowerShell原生布尔值 $body_json = [ordered]@{ "apikey" = "KEY" "from" = "FRNR" "to" = "TONR" "message" = "test" "twoway" = $false "conversation" = "CONV123" "checknumber" = $true } | ConvertTo-Json Invoke-RestMethod -Uri $url -Method Post -Body $body_json -ContentType "application/json"
其他排查方向
- 检查JSON序列化深度:如果后续有嵌套结构,
ConvertTo-Json默认深度是2,可能导致部分内容被截断,需要加上-Depth参数(比如ConvertTo-Json -Depth 10) - 对比Postman的请求头:打开Postman的请求详情,查看所有请求头(比如
Accept、User-Agent等),在PowerShell里用-Headers参数补充这些头,确保和Postman一致:$headers = @{ "Accept" = "application/json" "User-Agent" = "PostmanRuntime/7.32.3" # 换成你Postman里的实际User-Agent } Invoke-RestMethod -Uri $url -Method Post -Body $body_json -ContentType "application/json" -Headers $headers - 查看实际发送的请求内容:用
-Verbose参数输出请求详情,对比Postman的Raw请求体,确认JSON格式完全一致:Invoke-RestMethod -Uri $url -Method Post -Body $body_json -ContentType "application/json" -Verbose
内容的提问来源于stack exchange,提问作者Mike Trott
相关产品推荐
相关产品推荐

