快速入门:使用必应视频搜索 REST API 和 C# 来搜索视频
警告
2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅必应搜索 API 文档。 关于为必应搜索创建新的 Azure 资源的说明,请参阅通过 Azure 市场创建必应搜索资源。
根据此快速入门中的说明对必应视频搜索 API 进行第一次调用。 这个简单的 C# 应用程序会向该 API 发送一个 HTTP 视频搜索查询并显示 JSON 响应。 虽然此应用程序是使用 C# 编写的,但 API 是一种 RESTful Web 服务,与大多数编程语言兼容。
GitHub 上提供了此示例的源代码以及更多的错误处理、功能和代码注释。
先决条件
必须将计算机设置为运行 .Net Core。 有关安装说明,请访问 .NET Core 下载页。 可以在 Windows、Linux、macOS 或 Docker 容器中运行此应用程序。 必须安装常用的代码编辑器。 在以下说明中,我们使用的是开放源代码跨平台编辑器 Visual Studio Code。 不过,你可以使用习惯使用的任意工具。
创建 Azure 资源
通过创建以下 Azure 资源之一开始使用必应视频搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
创建并初始化项目
第一步是新建应用程序。 打开命令提示符,然后新建应用程序的目录。 将新建的目录设为当前目录。 在控制台窗口中输入以下命令:
dotnet new console --name VideoSearchClient
需要在 Main 方法的顶部添加以下 using
指令,以便 C# 编译器识别 Task 和 JSON 类型:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
为你的订阅密钥、终结点和搜索词添加变量。 对于 uriBase
值,可以使用以下代码中的全局终结点,或者使用资源的 Azure 门户中显示的自定义子域终结点。
// Replace the accessKey string value with your valid access key.
const string _accessKey = "enter your key here";
// Or use the custom subdomain endpoint displayed in the Azure portal for your resource.
const string _uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/videos/search";
const string _searchTerm = "kittens";
接下来,更新 Main 方法,以便使用 Async 方法。 添加 async 修饰符,并将返回类型更改为 Task。
static async Task Main(string[] args)
{
}
现在,你有了一个除了以异步方式执行操作之外不执行任何操作的程序。 现在进行改进。
创建一个数据结构来保存必应视频搜索 API 响应
定义 SearchResult
和 Video
类以包含视频搜索结果。 以后如果需要 JSON 结果中的其他字段,则可添加更多属性。
class SearchResult
{
[JsonPropertyName("totalEstimatedMatches")]
public int TotalEstimatedMatches { get; set; }
[JsonPropertyName("value")]
public List<Video> Videos { get; set; }
}
class Video
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
[JsonPropertyName("thumbnailUrl")]
public string ThumbnailUrl { get; set; }
[JsonPropertyName("contentUrl")]
public string ContentUrl { get; set; }
}
创建和处理视频搜索请求
我们使用 HttpClient
来执行对 API 的调用。 首先,需要添加标头 Ocp-Apim-Subscription-Key
和访问密钥。
using var client = new HttpClient();
client.BaseAddress = new Uri(_uriBase);
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _accessKey);
构造搜索请求的 URI。 在将搜索词 _searchTerm
追加到字符串之前,先对其进行格式化。
var response = await client.GetAsync($"?q={Uri.EscapeDataString(_searchTerm)}");
处理结果
响应成功后,就可以处理 JSON 数据。 我们将 JSON 字符串反序列化为我们之前创建的 SearchResult
。 循环到结果(如果有),然后将结果输出到控制台。
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<SearchResult>(json);
foreach (var video in result.Videos)
{
Console.WriteLine($"Name: {video.Name}");
Console.WriteLine($"ContentUrl: {video.ContentUrl}");
Console.WriteLine();
}
}
示例 JSON 响应
在 JSON 中返回成功的响应,如以下示例所示:
{
"_type": "Videos",
"instrumentation": {},
"readLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?q=kittens",
"webSearchUrl": "https://www.bing.com/videos/search?q=kittens",
"totalEstimatedMatches": 1000,
"value": [
{
"webSearchUrl": "https://www.bing.com/videos/search?q=kittens&view=...",
"name": "Top 10 cute kitten videos compilation",
"description": "HELP HOMELESS ANIMALS AND WIN A PRIZE BY CHOOSING...",
"thumbnailUrl": "https://tse4.mm.bing.net/th?id=OVP.n1aE_Oikl4MtzBb...",
"datePublished": "2014-11-12T22:47:36.0000000",
"publisher": [
{
"name": "Fabrikam"
}
],
"creator": {
"name": "Marcus Appel"
},
"isAccessibleForFree": true,
"contentUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
"hostPageUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
"encodingFormat": "h264",
"hostPageDisplayUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
"width": 480,
"height": 360,
"duration": "PT3M52S",
"motionThumbnailUrl": "https://tse4.mm.bing.net/th?id=OM.j4QyJAENJphdZQ_1501386166&pid=Api",
"embedHtml": "<iframe width=\"1280\" height=\"720\" src=\"https://www.fabrikam.com/embed/8HVWitAW-Qg?autoplay=1\" frameborder=\"0\" allowfullscreen></iframe>",
"allowHttpsEmbed": true,
"viewCount": 7513633,
"thumbnail": {
"width": 300,
"height": 168
},
"videoId": "655D98260D012432848F6558260D012432848F",
"allowMobileEmbed": true,
"isSuperfresh": false
},
. . .
],
"nextOffset": 36,
"queryExpansions": [
{
"text": "Kittens Meowing",
"displayText": "Meowing",
"webSearchUrl": "https://www.bing.com/videos/search?q=Kittens+Meowing...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
"thumbnail": {
"thumbnailUrl": "https://tse3.mm.bing.net/th?q=Kittens+Meowing&pid..."
}
},
{
"text": "Funny Kittens",
"displayText": "Funny",
"webSearchUrl": "https://www.bing.com/videos/search?q=Funny+Kittens...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
"thumbnail": {
"thumbnailUrl": "https://tse3.mm.bing.net/th?q=Funny+Kittens&..."
}
},
. . .
],
"pivotSuggestions": [
{
"pivot": "kittens",
"suggestions": [
{
"text": "Cat",
"displayText": "Cat",
"webSearchUrl": "https://www.bing.com/videos/search?q=Cat...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?...",
"thumbnail": {
"thumbnailUrl": "https://tse3.mm.bing.net/th?q=Cat&pid=Api..."
}
},
{
"text": "Feral Cat",
"displayText": "Feral Cat",
"webSearchUrl": "https://www.bing.com/videos/search?q=Feral+Cat...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
"thumbnail": {
"thumbnailUrl": "https://tse3.mm.bing.net/th?q=Feral+Cat&pid=Api&..."
}
}
]
}
],
"relatedSearches": [
{
"text": "Kittens Being Born",
"displayText": "Kittens Being Born",
"webSearchUrl": "https://www.bing.com/videos/search?q=Kittens+Being+Born...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?...",
"thumbnail": {
"thumbnailUrl": "https://tse1.mm.bing.net/th?q=Kittens+Being+Born&pid=..."
}
},
. . .
]
}