【问题标题】:How to send UTF8 to the WordPress REST-API?如何将 UTF8 发送到 WordPress REST-API?
【发布时间】:2019-02-14 02:52:47
【问题描述】:

格式错误的 UTF-8 字符,可能编码不正确

免责声明:字符编码让我很困惑。
我想通过 WordPress REST-API 自动创建很多帖子。我可以毫无问题地创建帖子 - 除非我的内容中有 特殊 字符。例如表情符号。

$params = @{
    title = $Title
    content = $Content # "foobar" would work just fine; 
                       # "????äöü" will give me an error
}

Invoke-RestMethod -Uri "https://my.blog.foo/wp-json/v2/posts" `
                  -Method POST `
                  -Headers @{ Authorization = ("Basic {0}" -f $ACCESS_TOKEN) } ` 
                  -ContentType "application/json" `
                  -UseBasicParsing `
                  -Body $($params | ConvertTo-Json) 

我认为这实际上不是与 WordPress 相关的问题。无论如何,我现在摆弄了很长一段时间,我只是想不出一种方法来发送我的内容而不会出现错误(“ö”得到“?”)它。

【问题讨论】:

  • 请改用-ContentType "application/json; charset=utf-8"。如果这仍然不起作用,请查看stackoverflow.com/q/21598398/934946 以了解您可以采取的其他操作(例如编码正文/添加内容类型标头)

标签: json wordpress rest powershell


【解决方案1】:

请改用-ContentType "application/json; charset=utf-8";

如果它不起作用,您可能还需要将您的身体编码为 UTF8。 $body = [System.Text.Encoding]::UTF8.GetBytes($body);

完整示例

$params = @{
    title = $Title
    content = $Content # "foobar" would work just fine; 
                       # "?äöü" will give me an error
}

$Body = $params | ConvertTo-Json
$Body = [System.Text.Encoding]::UTF8.GetBytes($body)

$Splat_Post= @{
    ContentType = "application/json; charset=utf-8"
    UseBasicParsing = $true
    Method = 'POST'
    Uri = "https://my.blog.foo/wp-json/v2/posts"
    Headers = @{ Authorization = ("Basic {0}" -f $ACCESS_TOKEN) }
}

Invoke-RestMethod @Splat_Post-Body $Body

注意:我修改了代码来演示 splatting

如果您每次都需要使用所有相同的参数调用该方法,除了 body,您可以这样调用它: Invoke-RestMethod @Splat_Post -Body $Body 然后每次只需将 $Body 更改为您想要的内容。

【讨论】:

    【解决方案2】:

    您可以在发布之前尝试将正文编码为 UTF8

    -Body ([System.Text.Encoding]::UTF8.GetBytes(($params | ConvertTo-Json)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-30
      • 2018-06-30
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多