使用Api键我可以从 Api Explorer 中获取播放列表中的视频。 不使用OAuth执行获取结果json。这是链接。
https://developers.google.com/apis-explorer/?hl=en_US#p/youtube/v3/youtube.playlistItems.list?part=snippet&playlistId=PLHyTuYqPkZCzt7mWZ4hmmrRdjLJiw6O2T&_h=2&
使用Go on App引擎实现相同的调用失败,错误如下:
Get https://www.googleapis.com/youtube/v3/playlistItems?alt=json&part=snippet&playlistId=PLHyTuYqPkZCzt7mWZ4hmmrRdjLJiw6O2T: http.DefaultTransport and http.DefaultClient are not available in App Engine. See https://cloud.google.com/appengine/docs/go/urlfetch/
这是我使用的代码:
import (
"net/http"
"code.google.com/p/google-api-go-client/googleapi/transport"
"code.google.com/p/google-api-go-client/youtube/v3"
"log"
)
var service *youtube.Service
func init() {
var err error
log.Println("Apikey = ", apiKey)
client := &http.Client{Transport: &transport.APIKey{Key: apiKey}}
service, err = youtube.New(client)
if err != nil {
log.Println("ERROR in creating youtube New client ", err)
}
var items *youtube.PlaylistItemListResponse
if items, err = service.PlaylistItems.List("snippet").PlaylistId("PLHyTuYqPkZCzt7mWZ4hmmrRdjLJiw6O2T").Do(); err != nil {
log.Println("Error in fetching playlist items ", err) //this line shows the error
}
log.Println(Jsonify(items))
}
截至目前,我在本地开发服务器上运行我的代码,即 goapp serve
缺少什么?如何使用v3 api和ApiKey获取youtube播放列表视频?
答案 0 :(得分:0)
不幸的是,链接的文档并没有解释为什么你的代码不起作用。在App Engine上,您需要使用http.Transport
包提供的特殊urlfetch
;见https://cloud.google.com/appengine/docs/go/urlfetch/
答案 1 :(得分:0)
找到解决方案。下面的代码为我完成了任务。
func FetchVideos(w http.ResponseWriter, r *http.Request) {
var service *youtube.Service
ctx := appengine.NewContext(r)
transport := &transport.APIKey{
Key: apiKey,
Transport: &urlfetch.Transport{Context: ctx}}
client := &http.Client{Transport: transport}
var err error
service, err = youtube.New(client)
if err != nil {
log.Println("ERROR in creating youtube New client ", err)
}
var items *youtube.PlaylistItemListResponse
if items, err = service.PlaylistItems.List("snippet").PlaylistId("PLHyTuYqPkZCzt7mWZ4hmmrRdjLJiw6O2T").Do(); err != nil {
log.Println("Error in fetching playlist items ", err)
}
log.Println(Jsonify(items))