Invoke-RestMethod utf8 字符?

问题描述 投票:0回答:4

我正在从

Invoke-RestMethod
执行 PUT,但端点不喜欢我的瑞典字符 åäö。 我已经在我的 Windows CMD 窗口上通过下载的 curl 进行了验证,并得到了相同的结果错误 400。奇怪的是它可以在我的计算机上的 PostMan 上运行。 会不会和utf8、BOM有关系?尝试将其从我的字符串中删除,但没有帮助。

不工作:

{    "User":  {
                 "email":  "[email protected]",
                 "last_name":  "Åkesson",
                 "first_name":  "Thomas",
                 "enabled":  true
             }
}

工作:

{
    "User":  {
                 "email":  "[email protected]",
                 "last_name":  "akesson",
                 "first_name":  "Thomas",
                 "enabled":  true
             }
}

问题对我来说似乎与将 PowerShell 的默认输出编码更改为 UTF-8有关? 或者端点本身是否有一些错误?

json powershell encoding
4个回答
7
投票

用这一行解决了它:

$body = [System.Text.Encoding]::UTF8.GetBytes($json)

答案:微软:Invoke-RestMethod 和 UTF-8 数据


2
投票

当我尝试使用 PowerShell 在团队中发布内容时,遇到了丹麦字符的问题

åæø
。我发现解决方案是在调用中包含字符编码:

$FilePath = '.\body.txt'
$fileContent = Get-Content -Path $FilePath -Encoding UTF8 
Write-host $fileContent
Invoke-RestMethod -ContentType "application/json; charset=windows-1252" -Uri "https://example.webhook.office.com/webhookb2" -Method 'Post' -Body $fileContent

即包括

charset=windows-1252
对我来说是成功的。


0
投票

对我来说,这种方法很有效(场景是从 WordPress 中提取的)。请参阅下面的 Get-Content '文件路径' -Encoding UTF8。也许首先输出到 XML 是这里的关键?

#GET WordPress posts.
Invoke-RestMethod -Uri 'https://wordpress.com/category/feed/' -OutFile C:\PowerShell\MakeFeed.xml
#NOTE -Encoding UTF8 is crucial here / otherwise bad characters for superscript, quotes, etc.
[xml]$Content = Get-Content C:\PowerShell\MakeFeed.xml -Encoding UTF8

0
投票

我也花了很多时间在这上面,直到我显式添加了参数 -ComponentType = "charset..." 然后我的服务器 api 就能够比较 UTF8 字符串了。 请注意,添加标头或尝试使用 utf-8 对正文进行字符串编码不起作用。

$response= Invoke-RestMethod -Uri $endpoint-Method Post -Headers $headers -Body ($body | ConvertTo-Json -Depth 5) -ContentType "application/json; charset=utf-8"

© www.soinside.com 2019 - 2024. All rights reserved.