繁体   English   中英

为什么这个 Go/GraphQL 查询返回 HTTP 415 错误?

[英]Why is this Go/GraphQL query returning HTTP 415 error?

我正在尝试按照 Go/GraphQL 配方1连接到特定的 API。 以下在 Python/Jupyter 中有效:

import requests
import json

query = """query lineSearch {
  lines(transportModes: water) {
    id
    quays {
      name
      id
      latitude
      longitude
    }
    transportSubmode
  }
}"""

url = 'https://api.entur.io/journey-planner/v2/graphql'
r = requests.post(url, json={'query': query})
print(r.text)

以下 Go 尝试在 Goland IDE 中返回HTTP 415 Unsupported Media Type

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

func main() {
    jsonData := map[string]string{
        "query": `query {lines(transportModes: water) {id quays {name id latitude longitude} transportSubmode }}`,
    }
    jsonValue, _ := json.Marshal(jsonData)
    request, err := http.NewRequest("POST", "https://api.entur.io/journey-planner/v2/graphql",
        bytes.NewBuffer(jsonValue))
    client := &http.Client{Timeout: time.Second * 10}
    response, err := client.Do(request)
    defer response.Body.Close()
    if err != nil {
        fmt.Printf("The HTTP request failed with error %s\n", err)
    }
    data, _ := ioutil.ReadAll(response.Body)
    fmt.Println(string(data))
}

我是否犯了任何明显的 Python-to-Go 翻译错误?

您可能缺少标题Content-Type: application/json

只需添加

request.Header.Add("Content-Type", "application/json")

下面的请求创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM