Wrong encoding on PowerShell Invoke-WebRequest POST

a 夏天 提交于 2019-12-18 12:19:36

问题


I'm using Invoke-WebRequest POST method to send an text data. After sending the text in a wrong encoding.

Script:

$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"

Fiddler:

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

Edited:

It seems that it is necessary to first convert the text into utf8. PowerShell ISE uses a different encoding by default. In my case, 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"

回答1:


This worked for me:

$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"

Adding the charset=utf-8 fixed my issue where the acute accent characters were getting converted to special symbols.




回答2:


I had to do two things to solve the problem. Encode the body and add the charset to the header:

$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


来源:https://stackoverflow.com/questions/21598398/wrong-encoding-on-powershell-invoke-webrequest-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!