PowerShell中Invoke-RestMethod调用API时API Key授权失败
API密钥授权问题排查(PowerShell调用失败,Postman可成功)
我尝试调用某API时遇到API Key类型的授权问题,导致调用失败。Postman中可正常调用该API(附截图),但以下PowerShell代码无法正常运行:
$headers = @{Authorization="auth_token codeKeyhere"} $params = @{ Uri = 'endopointhere' Method = 'GET' ContentType = 'application/json' } $response = Invoke-RestMethod @params -Header $header $response
问题排查与修正方案
- 变量名拼写错误:代码中定义的请求头变量是
$headers,但调用Invoke-RestMethod时写的是-Header $header(少了末尾的s),这会导致授权头未正确传递。 - 请求头传递方式优化:可以直接将
Headers加入参数哈希表,避免单独传递时的拼写失误。 - 验证授权头格式:确认Postman中使用的
auth_token codeKeyhere格式完全匹配API要求,部分API可能要求Bearer前缀或其他格式,需严格对齐Postman的请求头内容。
修正后的代码示例
$headers = @{Authorization="auth_token codeKeyhere"} $params = @{ Uri = 'endopointhere' Method = 'GET' ContentType = 'application/json' Headers = $headers } $response = Invoke-RestMethod @params $response
内容的提问来源于stack exchange,提问作者juan perez
相关产品推荐
相关产品推荐

