json - Powershell Invoke-WebRequest 和字符编码

标签 json powershell character-encoding spotify

我正在尝试通过他们的 Web API 从 Spotify 数据库获取信息。 但是,我遇到了重音元音(ä、ö、ü 等)的问题

让我们以 Tiësto 为例。 Spotify 的 API Browser 可以正确显示信息: https://developer.spotify.com/web-api/console/get-artist/?id=2o5jDhtHVPhrJdv3cEQ99Z

如果我使用 Invoke-Webrequest 进行 API 调用我明白了

Ti??sto

作为名字:

function Get-Artist {
param($ArtistID = '2o5jDhtHVPhrJdv3cEQ99Z',
      $AccessToken = 'MyAccessToken')


$URI = "https://api.spotify.com/v1/artists/{0}" -f $ArtistID

$JSON = Invoke-WebRequest -Uri $URI -Headers @{"Authorization"= ('Bearer  ' + $AccessToken)} 
$JSON = $JSON | ConvertFrom-Json
return $JSON
}

enter image description here

如何获得正确的名称?

最佳答案

更新:PowerShell (Core) 7.3+ 现在在 HTTP 响应 header 中缺少(有效的)charset 属性时默认为 UTF-8,因此问题不再存在出现在那里。


Jeroen Mostert ,在对问题的评论中,很好地解释了问题:

The problem is that Spotify is (unwisely) not returning the encoding it's using in its headers. PowerShell obeys the standard by assuming ISO-8859-1, but unfortunately the site is using UTF-8. (PowerShell ought to ignore standards here and assume UTF-8, but that's just like, my opinion, man.) More details here, along with the follow-up ticket.

不需要使用临时文件的解决方法:

假设函数 ConvertTo-BodyWithEncoding 已定义(见下文),您可以使用以下内容:

# ConvertTo-BodyWithEncoding defaults to UTF-8.
$JSON = Invoke-WebRequest -Uri $URI ... | ConvertTo-BodyWithEncoding

便捷函数ConvertTo-BodyWithEncoding:

注意:

  • 函数手动解码构成给定响应正文的原始字节,默认为UTF-8,或者使用给定的编码,这可以指定为 [System.Text.Encoding] 实例、代码页编号(例如 1251)或编码 名称(例如,'utf-16le)。

  • 该函数也可用为an MIT-licensed Gist ,只有后者会继续保持。假设您已经查看了链接代码以确保它是安全的(我个人可以向您保证,但您应该始终检查),您可以直接如下定义(有关如何制作的说明将显示 future session 中可用的功能或将其转换为脚本):

    irm https://gist.github.com/mklement0/209a9506b8ba32246f95d1cc238d564d/raw/ConvertTo-BodyWithEncoding.ps1 | iex
    
function ConvertTo-BodyWithEncoding {

  [CmdletBinding(PositionalBinding=$false)]
  param(
    [Parameter(Mandatory, ValueFromPipeline)]
    [Microsoft.PowerShell.Commands.WebResponseObject] $InputObject,
    # The encoding to use; defaults to UTF-8
    [Parameter(Position=0)]
    $Encoding = [System.Text.Encoding]::Utf8
  )

  begin {
    if ($Encoding -isnot [System.Text.Encoding]) {
      try {
        $Encoding = [System.Text.Encoding]::GetEncoding($Encoding)
      }
      catch { 
        throw
      }
    }
  }

  process {
    $Encoding.GetString(
       $InputObject.RawContentStream.ToArray()
    )
  }

}

关于json - Powershell Invoke-WebRequest 和字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47952689/

相关文章:

javascript - 在没有 eval() 的情况下动态地将字符串评估为对象?

arrays - 在 Go 中解码 JSON 数组

ios - 使用带有添加的 WebAPI 参数的 NSDictionary

json - 如何显示自定义验证错误消息

powershell - 按类型组织文件

java - MimeMessage 内容传输编码问题

java - Java char 以什么编码存储?

mongodb - 使用来自 Powershell 的 shell --eval 开关调用 MongoDB 更新时遇到问题

powershell - 当我以这种方式请求 Get-Service 时,它​​会对我的姓名进行分组,我该如何防止这种情况发生?

Java OutputStreamWriter 默认字节顺序