使用API在YouTube上搜索.NET



我正在尝试使用YouTube API搜索带有搜索文本的YouTube。示例代码如下。

using Google.YouTube;
using Google.GData.YouTube;
using Google.GData.Client;
using Google.GData.Extensions;
(..)
YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
//order results by the number of views (most viewed first)
query.OrderBy = "viewCount";
// search for puppies and include restricted content in the search results
// query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
query.Query = "puppy";
query.SafeSearch = YouTubeQuery.SafeSearchValues.None;
Feed<Video> videoFeed = request.Get<Video>(query);
printVideoFeed(videoFeed);

我的问题是query.QueryrequestprintVideoFeed不存在——我如何使用API搜索YouTube?

虽然您可以为YouTube使用.NET客户端库,但我发现.NET API在协议本身中落后于正在进行的开发(例如,我不确定您是否还可以从API获得喜欢/不喜欢的信息(。

相反,我建议您使用数据API协议,它使用HTTP和XML(ATOM格式(,.NET具有可以轻松使用/解析的类。文档也非常完整,编写查询也非常容易。

在您的示例中,查询的URL为:

http://gdata.youtube.com/feeds/api/videos?v=2&orderby=viewCount&safeSearch=none&q=小狗

它随后会返回一个这样结构的XML文档(尽管数据可能不同,因为我假设小狗的新视频一直在上传(:

<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' 
    xmlns:app='http://www.w3.org/2007/app' 
    xmlns:media='http://search.yahoo.com/mrss/' 
    xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/'  
    xmlns:gd='http://schemas.google.com/g/2005' 
    xmlns:gml='http://www.opengis.net/gml'   
    xmlns:yt='http://gdata.youtube.com/schemas/2007'  
    xmlns:georss='http://www.georss.org/georss' 
    gd:etag='W/&quot;C0cBR38zfCp7I2A9WhdUEU4.&quot;'>
    <id>tag:youtube.com,2008:videos</id>
    <updated>2011-09-27T13:44:16.184Z</updated>
    <category scheme='http://schemas.google.com/g/2005#kind' 
        term='http://gdata.youtube.com/schemas/2007#video'/>
    <title>YouTube Videos matching query: puppy</title>
    <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo>
    <link rel='alternate' type='text/html' href='http://www.youtube.com'/>
...
    <entry gd:etag='W/&quot;CEINR347eCp7I2A9WhdUEEQ.&quot;'>
        <id>tag:youtube.com,2008:video:vkeETehk8C8</id>
        <published>2007-05-21T02:02:00.000Z</published>
        <updated>2011-09-27T03:03:16.000Z</updated>
        <category scheme='http://schemas.google.com/g/2005#kind' 
            term='http://gdata.youtube.com/schemas/2007#video'/>
...

如果您想利用他们已经拥有的对象模型,也可以获取XML并将其放入YouTube.NET客户端结构中,以便轻松访问(尽管不容易,但这是可能的(,但可以下拉到XML以获取API未公开的值。

您要查找的内容在.NET指南的"身份验证"一章中。

基本上,您需要在开始时添加以下内容:

YouTubeRequestSettings settings = new YouTubeRequestSettings("example app", clientID, developerKey);
YouTubeRequest request = new YouTubeRequest(settings);

printVideoFeed方法只是打印出所有元数据的演示,但您也可以在指南中找到它。你可能想用你得到的Feed做一些其他的事情。

query.Query不应该丢失。

最新更新