【问题标题】:Querying Shopify JSON data via the API with PowerShell (Error 401 with Invoke-Webrequest)使用 PowerShell 通过 API 查询 Shopify JSON 数据(Invoke-Webrequest 出现错误 401)
【发布时间】:2014-09-12 21:29:41
【问题描述】:

我正在尝试编写一个 PowerShell 脚本来使用 Shopify 的 API 来访问 JSON 数据。我创建了一个私有应用程序,并在通过浏览器访问 JSON 提要时确认它有效。我实际上也使用 System.Net.WebClient 完成了这项工作,但我更喜欢使用 Invoke-WebRequest 但这不能正确验证。

尝试时:

    $uri = "https://apikey:password@anewshop.myshopify.com/admin/products.json"
    $json = Invoke-WebRequest -Uri $uri -contentType "application/json" -Method Get -Headers @{"Host"="anewshop.myshopify.com";"Authorization"="Basic"} | ConvertFrom-Json

我收到错误 401:

System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()

通过 PowerShell 的身份验证失败,但使用浏览器则不会。在 Firefox 中发出请求时,请求头如下:

Host: "anewshop.myshopify.com"
User-Agent: "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language: "en-US,en;q=0.5"
Accept-Encoding: "gzip, deflate"
Cookie: "_secure_admin_session_id=35ce7a14ee4f510c2e20d57f66960503; request_method=GET"
Authorization: "Basic StrippedLongString="
Connection: "keep-alive"
Cache-Control: "max-age=0"

System.Net.WebClient 的工作代码如下:

$uri= "https://anewshop.myshopify.com/admin/products.json"
$apiKey = "apikey"
$password = "password"
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($apikey, $password)
$json = $webclient.DownloadString($fullurl) | ConvertFrom-Json

谁能解释为什么 Invoke-Webrequest 失败?它究竟缺少什么?额外的标题?

编辑:这也引发了一个额外的问题,即我将如何通过 API 实际更新数据。通常我会将 Invoke-Webreqest 与 POST/PUT 一起使用,但我不确定 WebClient 如何处理这种情况。

谢谢。

【问题讨论】:

  • 为什么两种方法的 URI 不同?您不需要调用与 WebClient 示例中相同的 URI 并将 apikey 和密码放在标题中吗?我不知道他们的 API,所以如果我弄错了,请纠正我。
  • 你的怀疑是对的。我曾假设 URi 中的 apikey/pass 会像在浏览器中一样工作(不知道我为什么得出这个结论)。我已经发布了答案。

标签: json powershell shopify


【解决方案1】:

通过确保 apikey 和密码在标头中采用 base64 编码解决:

$uri = "https://anewshop.myshopify.com/admin/products.json"
$apikey = "apikey"
$password = "password"
$headers = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($apikey+":"+$password))}
$products = Invoke-WebRequest -Uri $uri -contentType "application/json" -Method Get -Headers $headers | ConvertFrom-Json

【讨论】:

  • 这对我有用,因为上面由于某种原因切断了结果: $uri = "anewshop.myshopify.com/admin/products.json" $apikey = "apikey" $password = "password" $headers = @{" Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($apikey+":"+$password))} $result = Invoke-RestMethod -Method Get - Uri $resource -Header $headers
猜你喜欢
  • 2021-10-19
  • 1970-01-01
  • 2012-07-26
  • 2020-03-17
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
相关资源
最近更新 更多