PowerShell Invoke-RestMethod with post body that cause question mark problem

Version 7.3.0

LAI TOCA
2 min readApr 7, 2023
Photo from: https://blog.detectify.com/2020/05/28/hiding-in-plain-sight-http-request-smuggling/

We have somehow need to invoke a HTTP request for testing, integration or robotic purposes. PowerShell provide diverse functions that help us make our developers’ life more easily. However, the below code snippet having an issue to deal with encoding problem:

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json; charset=utf-8")

$body = "{
`n `"Hello`":`"您好`"
`n}"

$response = Invoke-RestMethod 'https://www.toptal.com/developers/postbin/1680839008616-0910483819898' -Method 'POST' -Headers $headers -Body $body
$response | ConvertTo-Json

The Chinese inside the body “您好” (meaning in English: Hi) was convert to question mark as the issue described.

Seems that the function: “Invoke-RestMethod” default behavior doesn’t handle the encoding UTF-8 properly. So we need to modify the the code a little bit to enforce the function using UTF-8.

$body = "{
`n `"Hello`":`"您好`"
`n}"

$response = Invoke-RestMethod 'https://www.toptal.com/developers/postbin/1680839008616-0910483819898
' -Method 'POST' -ContentType 'application/json; charset=UTF-8' -Body $body
$response | ConvertTo-Json

As the result shown now the body could be exactly what it was.

The issue declare the PowerShell 7.4 preview version just resolved the problem. If you were curious, please give it an update then try it. But for me, I would rather not tight close to the version:(

Reference

--

--

LAI TOCA
LAI TOCA

Written by LAI TOCA

Coding for fun. (Either you are running for food or running for being food.)

No responses yet