Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Invoke-RestMethod to GitLab API causes mojibake

Context

In PowerShell, You can call REST API with Invoke-RestMethod like:

Invoke-RestMethod -Headers $headers -Method Get -Timeout 10 -Uri "https://api.github.com/users/octocat/orgs"

Problem

The result of Invoke-RestMethod causes mojibake when the response contains non-ASCII characters like Japanese/Chinese characters.

Reason

  • Invoke-RestMethod treats the charset of the HTTP response as ISO-8859-1 rather than UTF-8, when the response doesn't have Content-Type: ... charset=utf-8 in HTTP header.
  • The response of GitLab API doesn't have Content-Type HTTP header.

Solution

Use Invoke-WebRequest rather than Invoke-RestMethod. You can decode the content of HTTP response as UTF-8 explicitly.

$res = (Invoke-WebRequest -Headers $headers -Method Get -Timeout 10-Uri "https://gitlab.example.com/api/v4/projects")
$con = [System.Text.Encoding]::Utf8.GetString([System.Text.Encoding]::GetEncoding("ISO-8859-1").GetBytes($res.Content))
ConvertFrom-Json $con