【发布时间】: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