如何从youtube获取我的YouTube视频列表?

时间:2015-06-15 15:35:59

标签: c# .net winforms youtube youtube-api

我安装了google api 3和OAuth2。 我尝试了谷歌开发的例子:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;



namespace Youtube_Manager
{
    public partial class Form1 : Form
    {
        string devKey = "mykey";
        string userName = "my gmail as login";
        string Password = "mypass";
        string feedUrl = "https://gdata.youtube.com/feeds/api/users/default/playlists?v=2";
        YouTubeRequestSettings settings;

        public Form1()
        {
            InitializeComponent();

            settings = new YouTubeRequestSettings("Youtube Uploader", devKey);
            YouTubeRequest request = new YouTubeRequest(settings);

            Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
            printVideoFeed(videoFeed);


        }

        static string auth;
        static void printVideoFeed(Feed<Video> feed)
        {
            foreach (Video entry in feed.Entries)
            {
                auth = entry.Author;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

第一个问题是链接https://gdata.youtube.com/feeds/api/users/default/playlists?v=2需要登录和密码我想在尝试浏览到这个链接时我会得到:

需要用户身份验证。 错误401

第二个问题是我不确定我是否使用了正确的密钥。 我的应用程序名称是Youtube Uploader所以我去了谷歌控制台: https://console.developers.google.com

在左侧我点击了apis并启用:youtube data api v3 并且还启用了YouTube Analytics API

然后我点击了Credentials,我为OAuth创建了密钥,所以我现在有了客户端ID密钥电子邮件地址密钥和证书指纹

然后在它下面我创建了公共api访问,我有Api密钥。

然后我以https://code.google.com/apis/youtube/dashboard/gwt/index.html#product

开始访问此网站

在那里,我看到了我的开发人员密钥,我还没有在我的csharp代码中使用它。

现在我想做的第一件事就是获取我已经上传到YouTube的我自己的视频列表,使用我今天/当前登录和密码,在这种情况下使用Daniel Lipman这个名字,当我登录时我正在使用我的gmail chocolade13091972@gmail.com 几年前我添加了一些视频。

所以问题是链接需要登录名和密码。并且不确定如何在我的代码中使用我的开发人员密钥用户名和密码。

我忘了提到,只是现在我发现了与我的开发人员密钥的链接,直到现在我尝试使用devKey我的客户端ID密钥,我想我错了。现在我找到了我的开发人员密钥长键。

修改

我现在尝试了这个:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Threading;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.MediaRss;

namespace Youtube_Manager
{
    public partial class Form1 : Form
    {
        List<string> results = new List<string>();
        string devKey = "dev key";
        string apiKey = "api key";
        string userName = "my gmail address";
        string Password = "pass";

        public Form1()
        {
            InitializeComponent();

            Run();


        }

        private async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows for read-only access to the authenticated 
                    // user's account, but not other types of account access.
                    new[] { YouTubeService.Scope.YoutubeReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });

            var channelsListRequest = youtubeService.Channels.List("contentDetails");
            channelsListRequest.Mine = true;

            // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
            var channelsListResponse = await channelsListRequest.ExecuteAsync();

            foreach (var channel in channelsListResponse.Items)
            {
                // From the API response, extract the playlist ID that identifies the list
                // of videos uploaded to the authenticated user's channel.
                var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

                Console.WriteLine("Videos in list {0}", uploadsListId);

                var nextPageToken = "";
                while (nextPageToken != null)
                {
                    var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
                    playlistItemsListRequest.PlaylistId = uploadsListId;
                    playlistItemsListRequest.MaxResults = 50;
                    playlistItemsListRequest.PageToken = nextPageToken;

                    // Retrieve the list of videos uploaded to the authenticated user's channel.
                    var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();

                    foreach (var playlistItem in playlistItemsListResponse.Items)
                    {
                        // Print information about each video.
                        //Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
                        results.Add(playlistItem.Snippet.Title);
                    }

                    nextPageToken = playlistItemsListResponse.NextPageToken;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

但它不会做任何不抛出异常或错误的事情。 我在线上使用了一个断点:

using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))

在这一行之后没有任何事情发生,它显示了form1,就是这样。

现在在构造函数中我改变并做了:

this.Run().Wait();

现在我在这条线上得到例外:

this.Run().Wait();

System.AggregateException was unhandled
  HResult=-2146233088
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
       at System.Threading.Tasks.Task.Wait()
       at Youtube_Manager.Form1..ctor() in d:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\Form1.cs:line 43
       at Youtube_Manager.Program.Main() in d:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.IO.FileNotFoundException
       HResult=-2147024894
       Message=Could not find file 'D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json'.
       Source=mscorlib
       FileName=D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json
       StackTrace:
            at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
            at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
            at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
            at Youtube_Manager.Form1.<Run>d__1.MoveNext() in d:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\Form1.cs:line 51
       InnerException:

我在哪里找到这个文件:client_secrets.json这是问题吗?

1 个答案:

答案 0 :(得分:1)

您正在尝试调用不再存在的v2网址(以https://gdata开头的网址)。

此外,您获得开发人员密钥的位置也已弃用;您不会使用“开发人员密钥”,而是使用来自console.developers.google.com的API密钥 - 而不是客户端ID。您需要创建“用于公共访问的API密钥”。

完成所有这些后,请查看以下有效示例:https://developers.google.com/youtube/v3/code_samples/dotnet#retrieve_my_uploads