【问题标题】:Youtube Thumbnail upload Failing with APIYoutube缩略图上传失败与API
【发布时间】:2020-12-30 14:45:45
【问题描述】:

我正在尝试以这种方式上传 youtube 视频的缩略图:


import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

func main() {

    url := "https://www.googleapis.com/youtube/v3/thumbnails/set?videoId=kU7okI-_vvU&key=[API_KEY]Type=media"
    imageRef, err := os.Open("test.png")
    if err != nil {
        log.Fatal("os.Open", err)
    }
    rd := bufio.NewReader(imageRef)

    req, err := http.NewRequest("POST", url, rd)
    if err != nil {
        log.Fatal("http.NewRequest", err)
    }

    log.Println(req.Body)

    req.Header.Add("authorization", "Bearer [ACCESS_TOKEN]")
    req.Header.Add("content-type", "image/png")

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal("http.DefaultClient", err)
    }

    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        log.Fatal("ioutil.ReadAll", err)
    }

    fmt.Println(res)
    fmt.Println(string(body))

}

我收到了这样的回复:

  "error": {
    "code": 400,
    "message": "The request does not include the image content.",
    "errors": [
      {
        "message": "The request does not include the image content.",
        "domain": "youtube.thumbnail",
        "reason": "mediaBodyRequired",
        "location": "body",
        "locationType": "other"
      }
    ]
  }
}

我在 POST 请求中包含图像正文。然而,respose 说 “请求不包括图像内容。”。谁能帮忙解决这个问题。

API 要求最大文件大小为 2MB,我已确保这一点。

谢谢。

PS:虽然代码中没有显示,但结果是经过错误处理测试的。

【问题讨论】:

  • 请不要忽略错误。
  • @Marc 虽然代码中没有显示,但结果是经过错误处理测试的。我只是省略了这里以保持代码清晰。
  • 假设您正确检查了所有错误(这就是为什么最好将其放入代码中),尝试将 Content-Type 标头设置为 image/png
  • @Marc 感谢您的建议。但没有运气!它仍然抛出同样的错误。

标签: go youtube-data-api thumbnails


【解决方案1】:

使用裸 HTTP 方法调用 YouTube 数据 API 有时会非常棘手。

您应该改用Google API Client Library for Go。另请参阅official Go Quickstart

如果您坚持使用当前的代码,您需要具备以下条件:

  • 调用 URL 应包含参数uploadType=media,并且
  • Content-Type 标头应传递给 HTTP 调用,其值类型为 image/png(如上所述)。
  • Content-Length 标头也应由您的代码设置(因为这不是在 NewRequestWithContext 函数中完成的;另请参阅此函数的 doc,如下面的 @Peter 所示)。

您还必须更改您的 URL,因为根据 official doc,API 端点的 URL 是:

https://www.googleapis.com/upload/youtube/v3/thumbnails/set.

请注意您的 URL 缺少 /upload/ 路径组件。

【讨论】:

猜你喜欢
  • 2013-08-25
  • 2021-06-13
  • 2021-10-07
  • 2021-05-21
  • 2015-08-11
  • 2019-08-23
  • 2013-07-15
  • 2010-11-14
  • 2012-05-21
相关资源
最近更新 更多