Bing API 实战 - C#






4.61/5 (17投票s)
一篇简短的文章,解释如何在 C#.NET 中使用 Bing API。
引言
根据 Bing 的说法,“Bing 是一个搜索引擎,它可以查找并整理您需要的答案,以便您做出更快、更明智的决策”。微软将其 API 公开,以便我们可以在自己的应用程序中使用它。本文档解释了如何创建一个使用 Bing 搜索功能的示例应用程序。
步骤 1
即使 Bing API 服务是免费的,您也需要一个应用程序 ID 才能使用该服务。您可以在这里创建它:http://www.bing.com/developers/createapp.aspx。
AppID 的格式如下:F2C2567D3A712A4E764C49473BF4AFF7F8722A4E。
注意:请勿使用此 ID,因为它是一个虚假的 AppID。请记住,您需要使用您的 Windows Live ID 登录。
第二步
现在,您可以创建一个 Windows 项目。(我使用了 Visual C# 2008 Express。)您需要添加一个 Web 引用到:http://api.search.live.net/search.wsdl?AppID=YourAppId。
将您的 AppId 替换到 YourAppId
中。我将其命名为 MyBingService
。您可以随意命名。
提示:您可以通过右键单击解决方案资源管理器中的项目节点 -> 添加服务引用 -> 高级... 按钮 -> 添加 Web 引用... 按钮来添加 Web 引用。
步骤 3
以下是示例代码。请注意,我仅使用了演示所需的代码/属性。有关完整信息,请参阅 Bing API 文档。
using System;
using System.Windows.Forms;
using WindowsFormsApplication1.MyBingService;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LiveSearchService service = new LiveSearchService();
SearchRequest request = new SearchRequest();
// use your Bing AppID
request.AppId = "put_your_AppID_her_please";
request.Query = "ninethsense"; // your search query
// I want to search only web
request.Sources = new SourceType[] { SourceType.Web };
SearchResponse response = service.Search(request);
foreach (WebResult result in response.Web.Results)
{
listBox1.Items.Add(result.Title + " URL: " + result.Url);
}
}
}
}
源代码解释
using WindowsFormsApplication1.MyBingService;
这是您在步骤 2 中添加的 Web 引用。
LiveSearchService service = new LiveSearchService();
我创建了一个 LiveSearchService
对象。
SearchRequest request = new SearchRequest();
request.AppId = "put_your_AppID_her_please"; // use your Bing AppID
request.Query = "ninethsense"; // your search query
// I want to search only web
request.Sources = new SourceType[] { SourceType.Web };
我创建了一个搜索查询 (request.Query
),使用 AppID
(request.AppId
),并指定我需要搜索网络、图像、视频等。
请参阅文档以获取所有可用的源类型。一些是
SourceType.Web
SourceType.Image
SourceType.Video
SourceType.Spell
SourceType.News
SourceTyp3.InstantAnswer
- 等等。
SearchResponse response = service.Search(request);
开始搜索!结果将在标识符 response
中可用。
foreach (WebResult result in response.Web.Results)
{
listBox1.Items.Add(result.Title + " URL: " + result.Url);
}
我将一个 ListBox
控件放置在窗体中以显示搜索数据。这段代码填充了 ListBox
。
步骤 4
没有步骤 4!只需执行该应用程序即可。
为什么没有附上源代码?
仅仅是因为我不喜欢随附我的个人 AppId :). 另外,我太懒了,没有编写自定义配置文件来存储它 - 这可能会使文章对于初学者来说过于复杂。 问我问题!我在这里。
有用链接
- Bing 开发人员中心 - http://www.bing.com/developers/
- 创建 AppId - http://www.bing.com/developers/createapp.aspx
- Bing API 版本 2.0 - http://msdn.microsoft.com/en-us/library/dd251056.aspx
- Bing 常见问题解答 - http://help.live.com/help.aspx?mkt=en-us&project=searchdevctr&querytype=keyword&query=faq
历史
- 2009 年 7 月 18 日:初始发布。