【发布时间】:2022-11-05 00:25:40
【问题描述】:
我的任务是为客户端编写一个脚本,该脚本依赖于对 API 的基本“GET”请求,该 API 返回一个 JSON 对象,我使用该对象中的信息进行后续调用。这很好,但要求发生了变化,现在我需要发送带有一些参数的请求。
在邮递员中进行了一些测试,当我在 Uri 末尾添加查询参数(即https://test.com/?type=image)时,调用效果很好,但是当我尝试更改 Invoke-WebRequest 中的 Uri 时,我得到一个“Invoke- RestMethod : 无效或过期的令牌'错误。当我取出参数时,它按预期工作,只是数据不正确。
我还尝试将查询参数转换为哈希表和 json,并将其作为正文发送,但仍然出现相同的错误。
我已经走到尽头了,任何见解都会受到赞赏。
什么有效
$baseUrl = 'https://test.com/api/v2/'
$method = 'GET'
$auth = Get-PSAuthorizationString -Uri $baseUrl -OauthConsumerKey $oauth_consumer_key -OauthConsumerSecret $oauth_consumer_secret -OauthAccessToken $oauth_token -OauthAccessTokenSecret $oauth_token_secret
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json")
$headers.Add("Authorization", $auth)
$responses = Invoke-RestMethod -Method $method -Headers $headers -Uri $baseUrl
是什么打破了它
$baseUrl = 'https://test.com/api/v2/?type=image'
$responses = Invoke-RestMethod -Method $method -Headers $headers -Uri $baseUrl
$body = @{}
$body['type']="image"
$responses = Invoke-RestMethod -Method $method -Headers $headers -Uri $baseUrl -body $body
【问题讨论】:
-
您可以尝试发布确切的命令吗?从你的帖子听起来它看起来像这样。 “调用 WebRequest -Uri “stackoverflow.com/?type=image”。这似乎工作得很好。可能是您请求的端点行为不同。或者它现在应该是一个带有正文而不是 GET 请求的 POST?
-
更新帖子以添加代码示例。这确实是一个 GET 请求。我认为这个问题与 Invoke-RestMethod 如何进行 URI 编码有关,但我似乎找不到任何确定的东西。
标签: powershell invoke-restmethod