使用PowerShell通过API查询Shopify JSON数据(使用Invoke-Webrequest的错误401)

时间:2014-09-12 21:29:41

标签: json powershell shopify

我正在尝试编写PowerShell脚本以使用Shopify的API来访问JSON数据。我已创建了一个私有应用,并确认在通过浏览器访问JSON Feed时此功能正常。我实际上也使用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实际更新数据。通常我会在POST / PUT中使用Invoke-Webreqest,但我不确定WebClient如何处理这种情况。

感谢。

1 个答案:

答案 0 :(得分:2)

通过确保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