如何在 PowerShell windows 中处理 curl 请求 headers

How to hand headers in curl request in PowerShell windows

curl -X POST <myUrl> -H "authorization: Bearer <valid token>"

但是当我发送它时出现异常 - 无法绑定参数 'Headers'。无法将类型“System.String”的“授权:Bearer”值转换为类型“System.Collections.IDictionary”

curl 是 Windows PowerShell 中 Invoke-WebRequest cmdlet 的别名。

如错误消息所示,所述 cmdlet 的 -Headers 参数接受 字典 header key-value 对。

要传递 Authorization header,您需要:

Invoke-WebRequest -Uri "<uri goes here>" -Method Post -Headers @{ Authorization = 'Bearer ...' } -UseBasicParsing

(请注意,我明确传递了 -UseBasicParsing 开关 - 如果没有,Windows PowerShell 将尝试使用 Internet Explorer 的 DOM 呈现来解析任何 HTML 响应引擎,在大多数情况下这可能不是您想要的)


如果您需要传递名称中带有 token-terminating 个字符(如 -)的 headers,请使用 ' 引号限定密钥:

$headers = @{ 
  'Authorization' = 'Bearer ...'
  'Content-Type'  = 'application/json'
}

Invoke-WebRequest ... -Headers $headers

如果 header order 很重要,请确保声明字典文字 [ordered]:

$headers = [ordered]@{ 
  'Authorization' = 'Bearer ...'
  'Content-Type'  = 'application/json'
}