首页 > 解决方案 > 使用 -ContentType 'application/json' 调用 WebRequest -Method 'POST' 失败

问题描述

使用时:

        $body = @{    
            Manager  = "spmigrationuser@contoso.com" #$item.PMEmail
            Name     = "some name"
            Number   = "Some number"
            Practice = "Some Practice"
        } 
$response = Invoke-RestMethod -Method Post -Uri $Url  -Body $body -ContentType 'application/json' # -Headers $Headers  

或者

$response = Invoke-WebRequest -Method 'POST' -Uri $Url  -Body $body -ContentType 'application/json' # -Headers $Headers  

ContentType 'application/json' 和 $Headers = @{'Content-Type' = 'application/json' } -Headers $Headers 都
不起作用

错误总是:

"Invoke-WebRequest : {"error":{"code":"InvalidRequestContent","message":"The request content is not valid and could not be deserialized: 'Error parsing NaN value. Path '', line 1, position 1.'."}}"

相同的调用在 Postman 中有效

我使用的是 PS 5.1,我必须有 -ContentType 'application/json' 否则 PS 工作但服务失败

可能是什么问题?

标签: powershellinvoke-restmethod

解决方案


我同意 NickSalacious 的观点。您的问题是您没有发送 JSON。

如果您正在使用 Postman 并且刚刚开始在 PowerShell 中执行 API。Postman 在请求的右上角有一个“代码”链接。就在发送按钮的下方和右侧。在那里你可以选择 PowerShell。这将为您了解如何在 PowerShell 中运行相同的请求提供良好的基础。

邮递员会把你的身体变成这样:

$body = "{`n    `"Manager`": `"spmigrationuser@contoso.com`",`n    `"Name`": `"some name`",`n    `"Number`": `"Some number`",`n    `"Practice`": `"Some Practice`"`n}"

这不是最容易使用和阅读的。从长远来看,学习和使用 ConvertTo-Json 将有更多帮助。

*编辑:还要查看 Invoke-RestMethod 和 Invoke-WebRequest。他们的行为不同,有时一个会比另一个更好。

*Edit2:我想我会举一个例子来说明另一种方法。

$request = @{
Uri         = 'http://YourURI.Here'
Headers     = @{ 'Authorization' = $token
                'AnotherHeader?' = 'Sure'}
Method      = 'POST'
Body = '{    
        "Manager": $item.PMEmail,
        "Name": "some name",
        "Number": "Some number",
        "Practice": "Some Practice"
        }'
ContentType = 'application/json'
}
$response = Invoke-RestMethod @request

推荐阅读