PowerShell中Invoke-RestMethod/Invoke-WebRequest波兰语字符显示异常
解决PowerShell中Invoke-WebRequest/Invoke-RestMethod获取波兰语变音符号乱码问题
核心原因
PowerShell默认会根据响应头的Content-Type推断编码,如果服务器未正确声明编码,或者PowerShell推断错误(比如误用Windows-1252而非UTF-8/ISO-8859-2),就会导致波兰语变音符号显示乱码。
解决方案
方法1:手动解码响应原始字节
绕过PowerShell自动编码解析,直接获取响应的原始字节,用指定编码解码:
# 发送请求获取原始响应 $response = Invoke-WebRequest 'https://<URL>/api/MethodInvoker/InvokeServiceMethod' -Method 'POST' -Headers $headers -Body $body # 优先尝试UTF-8解码(Postman正常显示大概率是UTF-8) $decodedContent = [System.Text.Encoding]::UTF8.GetString($response.Content) # 如果UTF-8无效,尝试波兰语常用的ISO-8859-2编码 # $decodedContent = [System.Text.Encoding]::GetEncoding("ISO-8859-2").GetString($response.Content) # 将解码后的内容转换为JSON对象(如果响应是JSON格式) $result = $decodedContent | ConvertFrom-Json
方法2:强制指定Invoke-RestMethod的响应编码
通过修改参数配置,强制Invoke-RestMethod使用目标编码解析响应:
# 临时设置默认参数,让Invoke-RestMethod使用UTF-8解析响应 $PSDefaultParameterValues['Invoke-RestMethod:ResponseEncoding'] = 'utf8' # 发送请求 $response = Invoke-RestMethod 'https://<URL>/api/MethodInvoker/InvokeServiceMethod' -Method 'POST' -Headers $headers -Body $body # 恢复默认配置(可选) $PSDefaultParameterValues.Remove('Invoke-RestMethod:ResponseEncoding')
方法3:添加Accept-Charset请求头
在请求头中明确告知服务器返回UTF-8编码的内容:
$headers = @{ "Content-Type"="application/json; charset=utf-8"; "OData-MaxVersion"="4.0"; "OData-Version"="4.0"; "Accept-Charset"="utf-8" # 强制服务器返回UTF-8编码 }; $response = Invoke-RestMethod 'https://<URL>/api/MethodInvoker/InvokeServiceMethod' -Method 'POST' -Headers $headers -Body $body
验证步骤
- 在Postman中查看响应头的
Content-Type字段,确认服务器实际返回的编码(比如charset=utf-8或charset=iso-8859-2)。 - 对应选择上述方法中的编码进行解码,确保和服务器返回的编码一致。
内容的提问来源于stack exchange,提问作者Hans Aben
相关产品推荐
相关产品推荐

