powershell - 使用 -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 工作但服务失败
可能是什么问题?
解决方案
我同意 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
推荐阅读
- php - 未定义属性:App\Notifications\NewUserNotification::$id
- word-embedding - 如何从 RoBERTa 获得每个单词(令牌)的单个嵌入向量?
- swiftui - SwiftUI:删除导航栏上方的空间
- r - R:保存循环的结果
- plugins - twilio flex 排队回调和语音邮件反应应用程序未创建任务
- rust - 如何在不换行的情况下读取用户的输入?
- android - 如何在 Android 中使用 Jsoup 抓取表的所有数据?
- javascript - 使用 projectname.urls 中定义的 URLconf,Django 尝试了这些 URL 模式,当前路径 appname/tablename/add/ 与其中任何一个都不匹配
- javascript - 如何在 Angular 中外部化 p-calendar 语言环境
- javascript - Footable 如何将行追加到顶部?