PowerShell调用REST API返回400错误,API页调用正常求助
PowerShell REST调用400 Bad Request问题修复
问题核心原因
你的代码中请求体(Body)的处理逻辑存在致命错误:
原代码里-Body $json | ConvertTo-Json -Depth 3的写法完全错误——管道符会把Invoke-RestMethod的执行结果传给ConvertTo-Json,而非先将$json对象转换为JSON字符串再作为请求体发送。这导致API收到的是未序列化的PowerShell对象,而非符合要求的JSON格式数据,因此返回400 Bad Request。
修正后的代码
方式1:提前转换JSON字符串
$username = "UserName" $password = ConvertTo-SecureString "Password" -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential($username, $password) $headers = @{ "accept" = "application/json" "X-API-Key" = "API-KEY" } # 先将导入的JSON对象转换为符合要求的JSON字符串 $jsonBody = $json | ConvertTo-Json -Depth 3 $response = Invoke-RestMethod -Uri "URI" ` -Method Post ` -Credential $credential ` -Headers $headers ` -ContentType "application/json" ` -Body $jsonBody
方式2:直接在Body参数中嵌套转换逻辑
$username = "UserName" $password = ConvertTo-SecureString "Password" -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential($username, $password) $headers = @{ "accept" = "application/json" "X-API-Key" = "API-KEY" } $response = Invoke-RestMethod -Uri "URI" ` -Method Post ` -Credential $credential ` -Headers $headers ` -ContentType "application/json" ` -Body ($json | ConvertTo-Json -Depth 3)
额外注意事项
- 移除原代码末尾多余的闭合大括号
},避免语法错误。 - 确保
$json是通过ConvertFrom-Json正确导入的对象,-Depth参数值需匹配JSON结构的嵌套层级,防止深层对象被截断。
内容的提问来源于stack exchange,提问作者Eric S
相关产品推荐
相关产品推荐

