快速入门:使用必应 Web 搜索 REST API 和 C# 搜索网页
警告
2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅必应搜索 API 文档。 关于为必应搜索创建新的 Azure 资源的说明,请参阅通过 Azure 市场创建必应搜索资源。
根据此快速入门中的说明对必应 Web 搜索 API 进行第一次调用。 这个 C# 应用程序会向该 API 发送一个搜索请求并显示 JSON 响应。 虽然此应用程序是使用 C# 编写的,但 API 是一种 RESTful Web 服务,与大多数编程语言兼容。
本快速入门中的此示例程序仅使用 .NET Core 类。
先决条件
下面是在开始本快速入门之前需要准备好的项目:
- Windows:Visual Studio 2017 或更高版本
- Linux/macOS:Visual Studio Code 和 .NET Core
- 免费的 Azure 订阅
创建 Azure 资源
通过创建以下 Azure 资源之一开始使用必应 Web 搜索 API:
- 在删除资源前,可通过 Azure 门户使用。
- 使用免费定价层试用该服务,稍后升级到用于生产的付费层。
- 在删除资源前,可通过 Azure 门户使用。
- 在多个 Azure AI 服务中对应用程序使用相同的密钥和终结点。
创建项目并声明依赖项
在 Visual Studio 或 VS Code 中创建控制台项目。 使用以下代码导入所需命名空间和类型:
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;
为程序声明命名空间和类
在本快速入门中,我们会将大多数代码置于 Program
类中。 首先,在项目中创建 BingSearchApiQuickstart
命名空间和 Program
类。
namespace BingSearchApisQuickstart
{
class Program
{
// The code in the following sections goes here.
}
}
定义变量
必须设置几个变量,然后才能继续操作。 将此代码添加到在上一部分中创建的 Program
类:
对于
uriBase
值,可以使用以下代码中的全局终结点,或者使用资源的 Azure 门户中显示的自定义子域终结点。确认
uriBase
有效并将accessKey
值替换为来自你的 Azure 帐户的订阅密钥。(可选)通过替换
searchTerm
的值自定义搜索查询。
// Enter a valid subscription key.
const string accessKey = "enter key here";
/*
* If you encounter unexpected authorization errors, double-check this value
* against the endpoint for your Bing Web search instance in your Azure
* dashboard.
*/
const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/search";
const string searchTerm = "Microsoft Cognitive Services";
声明 Main 方法
Main()
方法是必需的,是启动程序时调用的第一个方法。 在此应用程序中,main 方法会验证 accessKey
,发出一个请求,然后输出响应。
main()
方法依赖于在后续部分中创建的方法。
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
if (accessKey.Length == 32)
{
Console.WriteLine("Searching the Web for: " + searchTerm);
SearchResult result = BingWebSearch(searchTerm);
Console.WriteLine("\nRelevant HTTP Headers:\n");
foreach (var header in result.relevantHeaders)
Console.WriteLine(header.Key + ": " + header.Value);
Console.WriteLine("\nJSON Response:\n");
Console.WriteLine(JsonPrettyPrint(result.jsonResult));
}
else
{
Console.WriteLine("Invalid Bing Search API subscription key!");
Console.WriteLine("Please paste yours into the source code.");
}
Console.Write("\nPress Enter to exit ");
Console.ReadLine();
}
创建一个适用于搜索结果的结构
创建一个返回带相关标头的搜索结果的结构。 在向必应 Web 搜索 API 发出创建结果对象的请求时,将会调用它。
// Returns search results with headers.
struct SearchResult
{
public String jsonResult;
public Dictionary<String, String> relevantHeaders;
}
构造请求
请使用以下代码来构造搜索查询、执行 GET 请求和处理响应。
/// <summary>
/// Makes a request to the Bing Web Search API and returns data as a SearchResult.
/// </summary>
static SearchResult BingWebSearch(string searchQuery)
{
// Construct the search request URI.
var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);
// Perform request and get a response.
WebRequest request = HttpWebRequest.Create(uriQuery);
request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
// Create a result object.
var searchResult = new SearchResult()
{
jsonResult = json,
relevantHeaders = new Dictionary<String, String>()
};
// Extract Bing HTTP headers.
foreach (String header in response.Headers)
{
if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
searchResult.relevantHeaders[header] = response.Headers[header];
}
return searchResult;
}
设置响应的格式
此方法设置 JSON 响应的格式,主要是缩进和添加换行符。
/// <summary>
/// Formats the JSON string by adding line breaks and indents.
/// </summary>
/// <param name="json">The raw JSON string.</param>
/// <returns>The formatted JSON string.</returns>
static string JsonPrettyPrint(string json)
{
if (string.IsNullOrEmpty(json))
return string.Empty;
json = json.Replace(Environment.NewLine, "").Replace("\t", "");
StringBuilder sb = new StringBuilder();
bool quote = false;
bool ignore = false;
char last = ' ';
int offset = 0;
int indentLength = 2;
foreach (char ch in json)
{
switch (ch)
{
case '"':
if (!ignore) quote = !quote;
break;
case '\\':
if (quote && last != '\\') ignore = true;
break;
}
if (quote)
{
sb.Append(ch);
if (last == '\\' && ignore) ignore = false;
}
else
{
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
sb.Append(Environment.NewLine);
sb.Append(new string(' ', ++offset * indentLength));
break;
case ']':
case '}':
sb.Append(Environment.NewLine);
sb.Append(new string(' ', --offset * indentLength));
sb.Append(ch);
break;
case ',':
sb.Append(ch);
sb.Append(Environment.NewLine);
sb.Append(new string(' ', offset * indentLength));
break;
case ':':
sb.Append(ch);
sb.Append(' ');
break;
default:
if (quote || ch != ' ') sb.Append(ch);
break;
}
}
last = ch;
}
return sb.ToString().Trim();
}
将其放在一起
最后一步是运行代码。 如果希望将你的代码与我们的进行比较,请查看 GitHub 上的示例代码。
示例 JSON 响应
来自必应 Web 搜索 API 的响应以 JSON 形式返回。 此示例响应已截断,仅显示了单个结果。
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "Microsoft Cognitive Services"
},
"webPages": {
"webSearchUrl": "https://www.bing.com/search?q=Microsoft+cognitive+services",
"totalEstimatedMatches": 22300000,
"value": [
{
"id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0",
"name": "Microsoft Cognitive Services",
"url": "https://www.microsoft.com/cognitive-services",
"displayUrl": "https://www.microsoft.com/cognitive-services",
"snippet": "Knock down barriers between you and your ideas. Enable natural and contextual interaction with tools that augment users' experiences via the power of machine-based AI. Plug them in and bring your ideas to life.",
"deepLinks": [
{
"name": "Face",
"url": "https://azure.microsoft.com/services/cognitive-services/face/",
"snippet": "Add facial recognition to your applications to detect, identify, and verify faces using the Face service from Microsoft Azure. ... Cognitive Services; Face service;"
},
{
"name": "Text Analytics",
"url": "https://azure.microsoft.com/services/cognitive-services/text-analytics/",
"snippet": "Cognitive Services; Text Analytics API; Text Analytics API . Detect sentiment, ... you agree that Microsoft may store it and use it to improve Microsoft services, ..."
},
{
"name": "Computer Vision API",
"url": "https://azure.microsoft.com/products/ai-services?activetab=pivot:visiontab",
"snippet": "Extract the data you need from images using optical character recognition and image analytics with Computer Vision APIs from Microsoft Azure."
},
{
"name": "Emotion",
"url": "https://www.microsoft.com/cognitive-services/en-us/emotion-api",
"snippet": "Cognitive Services Emotion API - microsoft.com"
},
{
"name": "Bing Speech API",
"url": "https://azure.microsoft.com/services/cognitive-services/speech/",
"snippet": "Add speech recognition to your applications, including text to speech, with a speech API from Microsoft Azure. ... Cognitive Services; Bing Speech API;"
},
{
"name": "Get Started for Free",
"url": "https://azure.microsoft.com/services/cognitive-services/",
"snippet": "Add vision, speech, language, and knowledge capabilities to your applications using intelligence APIs and SDKs from Cognitive Services."
}
]
}
]
},
"relatedSearches": {
"id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches",
"value": [
{
"text": "microsoft bot framework",
"displayText": "microsoft bot framework",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+bot+framework"
},
{
"text": "microsoft cognitive services youtube",
"displayText": "microsoft cognitive services youtube",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+youtube"
},
{
"text": "microsoft cognitive services search api",
"displayText": "microsoft cognitive services search api",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+search+api"
},
{
"text": "microsoft cognitive services news",
"displayText": "microsoft cognitive services news",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+news"
},
{
"text": "ms cognitive service",
"displayText": "ms cognitive service",
"webSearchUrl": "https://www.bing.com/search?q=ms+cognitive+service"
},
{
"text": "microsoft cognitive services text analytics",
"displayText": "microsoft cognitive services text analytics",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+text+analytics"
},
{
"text": "microsoft cognitive services toolkit",
"displayText": "microsoft cognitive services toolkit",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+toolkit"
},
{
"text": "microsoft cognitive services api",
"displayText": "microsoft cognitive services api",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+api"
}
]
},
"rankingResponse": {
"mainline": {
"items": [
{
"answerType": "WebPages",
"resultIndex": 0,
"value": {
"id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0"
}
}
]
},
"sidebar": {
"items": [
{
"answerType": "RelatedSearches",
"value": {
"id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches"
}
}
]
}
}
}