You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)

额外注意事项

  1. 移除原代码末尾多余的闭合大括号},避免语法错误。
  2. 确保$json是通过ConvertFrom-Json正确导入的对象,-Depth参数值需匹配JSON结构的嵌套层级,防止深层对象被截断。

内容的提问来源于stack exchange,提问作者Eric S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 01:52:16