go - Youtube缩略图上传失败,API

标签 go youtube-data-api thumbnails

我正在尝试以这种方式上传 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 请求中包含图像正文。然而响应说“请求不包括图像内容。”。任何人都可以请帮忙。
API 要求最大文件大小为 2MB,我已确保这一点。
谢谢你。
PS:虽然代码中没有显示,但结果是经过错误处理测试的。

最佳答案

使用裸 HTTP 方法调用 YouTube 数据 API 有时会非常棘手。
您应该使用 Google API Client Library for Go反而。另见official Go Quickstart .
如果您坚持使用当前的代码,则需要具备以下条件:

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

  • 您还必须更改您的 URL,因为根据 official doc ,API 端点的 URL 是:https://www.googleapis.com/upload/youtube/v3/thumbnails/set .
    请注意您的 URL 缺少 /upload/路径组件。

    关于go - Youtube缩略图上传失败,API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63857870/

    相关文章:

    java - 使 jfilechooser 显示图像缩略图

    go - 从 sql 数据库 Golang 获取 blob

    google-app-engine - Permission Denied error 从 appengine go 调用外部服务

    go - 关闭 io.PipeWriter 是否关闭底层文件?

    youtube-api - 如何知道视频是否已被看到/隐藏?

    java - Youtube 搜索 :list getting PageInfo and nextPageToken null

    amazon-web-services - AWS mediaconvert 视频缩略图生成器会旋转吗?

    Android MediaStore : Images. Media.insertImage 与 ContentResolver.insert

    通过递归调用时 Go-routine 不运行

    python - 在 Python 上为 Django 实现 Youtube API v3 时出现问题(错误 : 'unicode' object has no attribute 'video' ))