Invoke-WebRequest 失败 - 使用 GitHub API "Problems parsing json"



我试图通过PowerShell与Graphql API通信。根据GitHub的说法,必须首先进行以下curl调用。

curl -H "Authorization: bearer token" -X POST -d " 
 { 
   "query": "query { viewer { login }}" 
 } 
" https://api.github.com/graphql

使用 github Enterprise ,在PowerShell上我进行以下调用:

$url = "http://github.company.com/api/graphql" # note that it's http, not https
$body = "`"query`":`"query { viewer { login }}`""                                               #`
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("content-type","application/json")
$headers.Add("Authorization","bearer myTokenNumber")
$response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $headers

我不断收到相同的错误消息,解析JSON存在问题。

我认为错误是body标签,但我看不到如何。

echo $body给出"query":"query { viewer { login }}"

这里有什么问题?

确切的错误消息:

Invoke-WebRequest : {"message":"Problems parsing JSON","documentation_url":"https://developer.github.com/v3"}
At line:1 char:13
+ $response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $heade ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

您的$body值是畸形的,因为它缺少封闭的{ ... }

使用此处的字符串使JSON字符串的构造更加容易:

$body = @'
{ "query": "query { viewer { login } }" }
'@

类似地,您可以用标志性文字简化构建标题:

$headers = @{
  "content-type" = "application/json"
  "Authorization" = "bearer myTokenNumber"
}

这是工作程序。感谢那些回答的人:

$url = "https://api.github.com/graphql" # regular github
# for enterprise it will be http(s)://[hostname]/api/graphql where hostname is 
# usually github.company.com ... try with both http and https
$body = @'
{ "query": "query { viewer { login } }" }
'@
$headers = @{
  "content-type" = "application/json"
  "Authorization" = "bearer tokenCode"
}
$response = Invoke-WebRequest -Uri $url -Method POST -Body $body -Headers $headers
Write-Host $response

输出:{"data":{"viewer":{"login":"yourGithubUsername"}}}

最新更新