簡體   English   中英

使用PowerShell通過API查詢Shopify JSON數據(Invoke-Webrequest錯誤401)

[英]Querying Shopify JSON data via the API with PowerShell (Error 401 with Invoke-Webrequest)

我正在嘗試編寫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如何處理這種情況。

謝謝。

通過確保在標題中將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM