【问题标题】:Powershell Invoke-WebRequest and character encodingPowershell Invoke-WebRequest 和字符编码
【发布时间】:2023-03-20 03:50:02
【问题描述】:

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

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

如果我使用 Invoke-Webrequest 进行 API 调用,我会得到 ​​p>

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
}

我怎样才能得到正确的名字?

【问题讨论】:

  • 问题在于 Spotify(不明智地)没有返回它在其标头中使用的编码。 PowerShell 通过假设 ISO-8859-1 来遵守标准,但不幸的是该站点使用的是 UTF-8。 (PowerShell 应该在这里忽略标准并假设 UTF-8,但这就像,我的意见,伙计。)更多细节here,以及后续票证。可能的解决方法here(但不幸的是,它们涉及放弃Invoke-WebRequest)。
  • 谢谢杰罗恩。我已经预料到了这一点。但是,我假设 Invoke-WebRequest 会有一个参数。我会尝试你的解决方法。很快就会报告。

标签: json powershell character-encoding spotify


【解决方案1】:

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

问题在于 Spotify(不明智地)没有返回它在其标头中使用的编码。 PowerShell 采用 ISO-8859-1 来遵守标准,但不幸的是该网站使用的是 UTF-8。 (PowerShell 应该在这里忽略标准并假设 UTF-8,但这就像,我的意见,伙计。)更多细节here,以及后续票证。

不需要使用临时文件的解决方法重新编码错误读取的字符串

如果我们假设存在一个函数convertFrom-MisinterpretedUtf8,我们可以使用以下内容:

$JSON = convertFrom-MisinterpretedUtf8 (Invoke-WebRequest -Uri $URI ...)

函数的定义见下文。


实用功能convertFrom-MisinterpretedUtf8:

function convertFrom-MisinterpretedUtf8([string] $String) {
  [System.Text.Encoding]::UTF8.GetString(
     [System.Text.Encoding]::GetEncoding(28591).GetBytes($String)
  )
}

该函数根据错误应用的编码 (ISO-8859-1) 将错误读取的字符串转换回字节,然后根据实际编码 (UTF-8) 重新创建字符串。

【讨论】:

    【解决方案2】:

    问题已通过 Jeron Mostert 提供的解决方法解决。 您必须将其保存在文件中并明确告诉 Powershell 它应该使用哪种编码。 这个解决方法对我有用,因为我的程序可以花费它需要的任何时间(关于读/写 IO)

    function Invoke-SpotifyAPICall {
    param($URI,
          $Header = $null,
          $Body = $null
          )
    
    if($Header -eq $null) {
        Invoke-WebRequest -Uri $URI -Body $Body -OutFile ".\SpotifyAPICallResult.txt"    
    } elseif($Body -eq $null) {
        Invoke-WebRequest -Uri $URI -Headers $Header -OutFile ".\SpotifyAPICallResult.txt"
    }
    
    $JSON = Get-Content ".\SpotifyAPICallResult.txt" -Encoding UTF8 -Raw | ConvertFrom-JSON
    Remove-Item ".\SpotifyAPICallResult.txt" -Force
    return $JSON
    
    }
    
    function Get-Artist {
        param($ArtistID = '2o5jDhtHVPhrJdv3cEQ99Z',
              $AccessToken = 'MyAccessToken')
    
    
        $URI = "https://api.spotify.com/v1/artists/{0}" -f $ArtistID
    
        return (Invoke-SpotifyAPICall -URI $URI -Header @{"Authorization"= ('Bearer  ' + $AccessToken)})
    }
    
    
    Get-Artist
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      相关资源
      最近更新 更多