如何用Invoke-RestMethod通过哈希表发送JSON体POST请求(无需手动编码)
问题解决:用哈希表发送JSON格式的POST请求(无需手动转JSON)
报错原因
你遇到的400错误有两个核心原因:
- 请求体格式不匹配:当指定
-ContentType "application/json"时,直接将哈希表传给-Body参数,PowerShell不会自动把哈希表序列化为JSON字符串,而是默认按x-www-form-urlencoded表单格式编码(比如生成displayName=xxx&startDateTime=xxx这样的字符串)。服务器收到这种格式的内容却试图按JSON解析,自然会触发"\u0027s\u0027 is an invalid start of a value"的解析错误。 - 必填字段缺失:报错里的
"The secret field is required."说明接口要求请求体中必须包含secret字段,你的哈希表里没加这个字段,所以即使格式正确也会报错。
解决方案
方案1:PowerShell 7.1+版本(推荐)
PowerShell 7.1及以上版本新增了-BodyAsJson参数,支持直接传入哈希表或自定义对象,PowerShell会自动将其序列化为JSON,并自动设置Content-Type: application/json请求头,无需手动转换:
$url = "${AppMgmtApiUrl}/api/v1/applications/resources/${ApiClientId}/secrets" $headers = @{} $body = @{ displayName = $secretDescription startDateTime = $startTime endDateTime = $endTime secret = "这里填写你的密钥内容" # 必须补充必填的secret字段 } $clientSecret = Invoke-RestMethod -Method Post -Uri $url -Authentication Bearer -Token $token -BodyAsJson $body -MaximumRetryCount 3 -ErrorAction Stop
方案2:PowerShell 5.1版本(兼容旧环境)
如果还在使用PowerShell 5.1,没有-BodyAsJson参数,只能手动将哈希表转换为JSON字符串后传入-Body:
$url = "${AppMgmtApiUrl}/api/v1/applications/resources/${ApiClientId}/secrets" $headers = @{} $body = @{ displayName = $secretDescription startDateTime = $startTime endDateTime = $endTime secret = "这里填写你的密钥内容" # 补充必填字段 } $bodyJson = $body | ConvertTo-Json -Compress $clientSecret = Invoke-RestMethod -Method Post -Uri $url -Authentication Bearer -Token $token -ContentType "application/json" -Headers $headers -Body $bodyJson -MaximumRetryCount 3 -ErrorAction Stop
内容的提问来源于stack exchange,提问作者Shuzheng
相关产品推荐
相关产品推荐

