【问题标题】:Invoke-WebRequest failed - "Problems parsing json" with GitHub apiInvoke-WebRequest 失败 - 使用 GitHub api “解析 json 的问题”
【发布时间】:2018-07-19 15:44:39
【问题描述】:

我正在尝试通过 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

【问题讨论】:

  • 你能分享一下确切的错误信息吗?
  • 请立即查看
  • 你在 GitHub 的 GraphQL Explorer Interface 中测试过你的令牌和查询吗?
  • 在那里完美运行
  • 你有理由必须使用http 版本吗?

标签: json powershell curl github graphql


【解决方案1】:

您的 $body 值是格式错误的 JSON,因为它缺少封闭的 { ... }

使用here-string 可以更轻松地构造 JSON 字符串:

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

同样,您可以使用 hashtable literal 简化构建标头:

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

【讨论】:

    【解决方案2】:

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

    $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"}}}

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 2016-07-15
      • 2017-04-06
      • 2021-11-07
      • 2021-07-22
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      相关资源
      最近更新 更多