【问题标题】:Wrong encoding on PowerShell Invoke-WebRequest POSTPowerShell Invoke-WebRequest POST 上的编码错误
【发布时间】:2021-03-30 20:07:03
【问题描述】:

我正在使用 Invoke-WebRequest POST 方法发送文本数据。以错误的编码发送文本后。

脚本:

$postData = "žluťoučký kůň úpěl ďábelské ódy"
Invoke-WebRequest -Uri 'http://www.mydomain.com/' -Method Post -Body $postData -ContentType "text/plain; charset=utf-8"

提琴手:

POST http://www.mydomain.com/ HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT; Windows NT 6.2; cs-CZ) WindowsPowerShell/4.0
Content-Type: text/plain; charset=utf-8
Host: www.mydomain.com
Content-Length: 31

zlutouck� kun �pel d�belsk� �dy

已编辑

看来需要先将文本转成utf8。默认情况下,PowerShell ISE 使用不同的编码。 在我的例子中,windows-1250。

$text = "žluťoučký kůň úpěl ďábelské ódy"
$postData = [System.Text.Encoding]::UTF8.GetBytes($text)
Invoke-WebRequest -Uri 'http://www.mydomain.com/' -Method Post -Body $postData -ContentType "text/plain; charset=utf-8"

【问题讨论】:

  • 请将您的编辑发布为您问题的答案; that's how we do things around here.
  • [System.Text.Encoding]::UTF8.GetBytes() 对我不起作用。输出类似于[29, 118, 61, 80, 267...]
  • PowerShell 版本对于本主题很重要。我可以在 PS 5.1 上将 UTF8 字符串作为帖子正文没有任何问题,但对于 PS 4.0,我需要将字符串保存到文件中,然后使用带有 -InFile 参数而不是 -Body 的 Web 请求

标签: powershell-3.0


【解决方案1】:

我必须做两件事来解决这个问题。对正文进行编码并将字符集添加到标题中:

$body = [System.Text.Encoding]::UTF8.GetBytes($body);

$headers = @{
            "Content-Type"="application/json; charset=utf-8";
            "OData-MaxVersion"="4.0";
            "OData-Version"="4.0";
        };

Invoke-WebRequest -Uri "$($odataEndpoint)systemusers($userid)" -Method PATCH -Headers $headers -Body $body -UseDefaultCredentials

【讨论】:

  • 我回复Headers: {[Connection, keep-alive], [Keep-Alive, timeout=5], [Content-Length, 7], [Content-Type, text/html; charset=utf-8],,我的请求是... -Headers @{'Content-Type'='application/json'}。我认为-headers 或 -contenttype` 无关紧要。
【解决方案2】:

这对我有用:

$postData = "žluťoučký kůň úpěl ďábelské ódy"
Invoke-WebRequest -Uri 'http://www.example.com/' -Method Post -Body $postData 
 -ContentType "text/plain; charset=utf-8"

添加 charset=utf-8 解决了我的尖锐重音字符被转换为特殊符号的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多