1

In powershell I am calling a rest API using Invoke-RestMethod. I am passing query string arguments whose values can have special characters and they are causing errors.

$x = Invoke-RestMethod -Uri "https://<something>.com?Key=<value>

Everything works fine as long as <value> is a normal string or numbers.

But if <value> contains any special characters like "a:1" or "a\u0000", it errors out stating

{"error":"bad_request","reason":"invalid UTF-8 JSON"}

I tried urlencoding the Uri but it doesn't work.

$encodedvalue = [System.Web.HttpUtility]::UrlEncode(<value>)
$x = Invoke-RestMethod -Uri "https://<something>.com?key=$encodedvalue

Any ideas/suggestions would be greatly appreciated

  • Can you try `[uri]::EscapeDataString()` ? P.S. You're missing a closing double-quote on the Invoke-RestMethod in both examples. – Theo Apr 07 '21 at 11:50

1 Answers1

0

I ended up using the below code snippet. This one handles the null character [uri]::EscapeUriString([System.Web.HttpUtility]::UrlEncode([char]0x0000)