如何让 youtube api 调用根据给定区域和 api 键获取类别?
How do I make youtube api call to get categories according to given region and api key?
我将此 class 添加到 form1:
public class YoutubeApiResponse
{
public string kind { get; set; }
public string etag { get; set; }
public string nextPageToken { get; set; }
public PageInfo pageInfo { get; set; }
public List<Item> items { get; set; }
}
列表中不存在变量项
然后在 form1 构造函数中我做了:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
if (response.IsSuccessStatusCode)
{
var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();
}
}
api 密钥无效 api 密钥,我只是随机更改了一些字母。
在这部分我遇到了错误:
var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();
YoutubeApiResponse 不存在,所以我将其更改为 YoutubeApiResponse,但这没有结果 属性。
此行的另一个错误:错误 2 'await' 运算符只能在异步方法中使用。考虑使用 'async' 修饰符标记此方法并将其 return 类型更改为 'Task'。
并且:
错误 1 'System.Net.Http.HttpContent' 不包含 'ReadAsAsync' 的定义,并且找不到接受类型 'System.Net.Http.HttpContent' 的第一个参数的扩展方法 'ReadAsAsync'(您是否缺少using 指令或程序集引用?)
我正在使用的 link 应该用于根据给定区域获取类别是:https://www.googleapis.com/youtube/v3/videoCategories?part=snippet®ionCode=IL&key=AIzaSyBgc1Gx-0tHbWp6-SWE0sQarpc6nGLtttt
在此示例中,区域代码 IL 和 api 密钥。
我只是不确定如何在我的 C# 代码中使用它。
这是我的 form1 代码:
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 System.Net.Http;
using System.Net.Http.Headers;
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 err1 = ""
string userName = "someone@gmail.com";
public Form1()
{
InitializeComponent();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
if (response.IsSuccessStatusCode)
{
var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();
}
}
UserCredential credential;
using (FileStream stream = new FileStream(@"D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore("YouTube.Auth.Store")).Result;
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public";
var filePath = @"C:\Users\bout0_000\Videos\test.mp4";//@"E:\video.mp4";
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
const int KB = 0x400;
var minimumChunkSize = 256 * KB;
var videosInsertRequest = youtubeService.Videos.Insert(video,
"snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged +=
videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived +=
videosInsertRequest_ResponseReceived;
// The default chunk size is 10MB, here will use 1MB.
videosInsertRequest.ChunkSize = minimumChunkSize * 4;
videosInsertRequest.Upload();
}
}
private static void videosInsertRequest_ResponseReceived(Video obj)
{
}
private static void videosInsertRequest_ProgressChanged(IUploadProgress obj)
{
}
private async Task Run()
{
UserCredential credential = null;
using (var stream = new FileStream(@"D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json", FileMode.Open, FileAccess.Read))
{
try
{
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())
);
}
catch (Exception errrr)
{
err1 = errrr.ToString();
}
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelsListRequest = youtubeService.Channels.List("snippet,contentDetails");
channelsListRequest.ForUsername = userName;
var channelsListResponse = await channelsListRequest.ExecuteAsync();
foreach (var channel in channelsListResponse.Items)
{
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistRequest = youtubeService.Playlists.List("id,snippet,contentDetails,status,player");
playlistRequest.Id = uploadsListId;
playlistRequest.MaxResults = 50;
playlistRequest.PageToken = nextPageToken;
var playlistListResponse = await playlistRequest.ExecuteAsync();
if (playlistListResponse.Items.Count > 0)
MessageBox.Show(playlistListResponse.Items[0].Snippet.Title);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
public class YoutubeApiResponse
{
public string kind { get; set; }
public string etag { get; set; }
public string nextPageToken { get; set; }
public PageInfo pageInfo { get; set; }
public List<Item> items { get; set; }
}
}
}
使用该部分根据给定的区域 ID 获取类别,然后将类别作为项目添加到 ComboBox,我不明白该怎么做。
你混淆了一些东西。
使用 public API 密钥进行身份验证:
/// <summary>
/// using Public APi key
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
/// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
/// <param name="userName">A string used to identify a user.</param>
/// <returns></returns>
public static YouTubeService AuthenticateOauth(string apiKey)
{
try
{
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
ApiKey = apiKey,
ApplicationName = "YouTube Data API Sample",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
验证
var service = Authentication.AuthenticateOauth("xxxxx8wFajmmARCqp7YdqkLmd1XYx7c");
发出请求:
var searchListRequest = service.Search.List("snippet");
searchListRequest.Q = "Google"; // Replace with your search term.
searchListRequest.MaxResults = 50;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = searchListRequest.Execute();
List<string> videos = new List<string>();
List<string> channels = new List<string>();
List<string> playlists = new List<string>();
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
case "youtube#channel":
channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
}
从示例项目中提取的代码 Google-dotnet-samples Youtube
更新视频类别示例:
var videoCatagories = service.VideoCategories.List("snippet");
videoCatagories.RegionCode = "IL";
var result = videoCatagories.Execute();
我将此 class 添加到 form1:
public class YoutubeApiResponse
{
public string kind { get; set; }
public string etag { get; set; }
public string nextPageToken { get; set; }
public PageInfo pageInfo { get; set; }
public List<Item> items { get; set; }
}
列表中不存在变量项
然后在 form1 构造函数中我做了:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
if (response.IsSuccessStatusCode)
{
var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();
}
}
api 密钥无效 api 密钥,我只是随机更改了一些字母。
在这部分我遇到了错误:
var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();
YoutubeApiResponse 不存在,所以我将其更改为 YoutubeApiResponse,但这没有结果 属性。
此行的另一个错误:错误 2 'await' 运算符只能在异步方法中使用。考虑使用 'async' 修饰符标记此方法并将其 return 类型更改为 'Task'。
并且:
错误 1 'System.Net.Http.HttpContent' 不包含 'ReadAsAsync' 的定义,并且找不到接受类型 'System.Net.Http.HttpContent' 的第一个参数的扩展方法 'ReadAsAsync'(您是否缺少using 指令或程序集引用?)
我正在使用的 link 应该用于根据给定区域获取类别是:https://www.googleapis.com/youtube/v3/videoCategories?part=snippet®ionCode=IL&key=AIzaSyBgc1Gx-0tHbWp6-SWE0sQarpc6nGLtttt
在此示例中,区域代码 IL 和 api 密钥。
我只是不确定如何在我的 C# 代码中使用它。 这是我的 form1 代码:
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 System.Net.Http;
using System.Net.Http.Headers;
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 err1 = ""
string userName = "someone@gmail.com";
public Form1()
{
InitializeComponent();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
if (response.IsSuccessStatusCode)
{
var youtubeResponse = await response.Content.ReadAsAsync < YoutubeApiResponse().Result();
}
}
UserCredential credential;
using (FileStream stream = new FileStream(@"D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore("YouTube.Auth.Store")).Result;
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public";
var filePath = @"C:\Users\bout0_000\Videos\test.mp4";//@"E:\video.mp4";
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
const int KB = 0x400;
var minimumChunkSize = 256 * KB;
var videosInsertRequest = youtubeService.Videos.Insert(video,
"snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged +=
videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived +=
videosInsertRequest_ResponseReceived;
// The default chunk size is 10MB, here will use 1MB.
videosInsertRequest.ChunkSize = minimumChunkSize * 4;
videosInsertRequest.Upload();
}
}
private static void videosInsertRequest_ResponseReceived(Video obj)
{
}
private static void videosInsertRequest_ProgressChanged(IUploadProgress obj)
{
}
private async Task Run()
{
UserCredential credential = null;
using (var stream = new FileStream(@"D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json", FileMode.Open, FileAccess.Read))
{
try
{
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())
);
}
catch (Exception errrr)
{
err1 = errrr.ToString();
}
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelsListRequest = youtubeService.Channels.List("snippet,contentDetails");
channelsListRequest.ForUsername = userName;
var channelsListResponse = await channelsListRequest.ExecuteAsync();
foreach (var channel in channelsListResponse.Items)
{
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistRequest = youtubeService.Playlists.List("id,snippet,contentDetails,status,player");
playlistRequest.Id = uploadsListId;
playlistRequest.MaxResults = 50;
playlistRequest.PageToken = nextPageToken;
var playlistListResponse = await playlistRequest.ExecuteAsync();
if (playlistListResponse.Items.Count > 0)
MessageBox.Show(playlistListResponse.Items[0].Snippet.Title);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
public class YoutubeApiResponse
{
public string kind { get; set; }
public string etag { get; set; }
public string nextPageToken { get; set; }
public PageInfo pageInfo { get; set; }
public List<Item> items { get; set; }
}
}
}
使用该部分根据给定的区域 ID 获取类别,然后将类别作为项目添加到 ComboBox,我不明白该怎么做。
你混淆了一些东西。
使用 public API 密钥进行身份验证:
/// <summary>
/// using Public APi key
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
/// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
/// <param name="userName">A string used to identify a user.</param>
/// <returns></returns>
public static YouTubeService AuthenticateOauth(string apiKey)
{
try
{
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
ApiKey = apiKey,
ApplicationName = "YouTube Data API Sample",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
验证
var service = Authentication.AuthenticateOauth("xxxxx8wFajmmARCqp7YdqkLmd1XYx7c");
发出请求:
var searchListRequest = service.Search.List("snippet");
searchListRequest.Q = "Google"; // Replace with your search term.
searchListRequest.MaxResults = 50;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = searchListRequest.Execute();
List<string> videos = new List<string>();
List<string> channels = new List<string>();
List<string> playlists = new List<string>();
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
case "youtube#channel":
channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
}
从示例项目中提取的代码 Google-dotnet-samples Youtube
更新视频类别示例:
var videoCatagories = service.VideoCategories.List("snippet");
videoCatagories.RegionCode = "IL";
var result = videoCatagories.Execute();