警告
2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅 必应搜索 API 文档。 有关为必应搜索创建新 Azure 资源的说明,请参阅 通过 Azure 市场创建必应搜索资源。
使用这份快速入门指南对必应视频搜索 API 进行首次调用。 这个简单的 C# 应用程序将 HTTP 视频搜索查询发送到 API 并显示 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# 编译器能够识别任务和 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 方法,以便可以使用异步方法。 添加异步修饰符,并将返回类型更改为 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=..."
}
},
. . .
]
}