我正在尝试使用 Bing Search API 在我的应用程序中查找作为背景的图片。我已将 BingSearchContainer.cs 包含在我的项目中,但我无法使其与此处提供的示例代码一起使用。
任何有关如何在我的 Windows Phone 8 应用程序中使用必应搜索 API 的指南都将被应用!
感谢您的回答。
最佳答案
我希望您已经有一个 AccountKey,所以我不会告诉您必须获得一个。
实现
- 首先,添加 BingSearchContainer.cs到你的项目
- 实现在 Bing API Quick Start & Code 中找到的示例 C# 代码
- 然后,右键单击References 并选择Manage NuGet Packages... 并搜索并安装
Microsoft.Data.Services.Client.WindowsP
。 修改示例代码,使其适用于 Windows Phone:
using Bing; using System; using System.Data.Services.Client; using System.Linq; using System.Net; namespace StackOverflow.Samples.BingSearch { public class Finder { public void FindImageUrlsFor(string searchQuery) { // Create a Bing container. string rootUri = "https://api.datamarket.azure.com/Bing/Search"; var bingContainer = new Bing.BingSearchContainer(new Uri(rootUri)); bingContainer.UseDefaultCredentials = false; // Replace this value with your account key. var accountKey = "YourAccountKey"; // Configure bingContainer to use your credentials. bingContainer.Credentials = new NetworkCredential(accountKey, accountKey); // Build the query. var imageQuery = bingContainer.Image(query, null, null, null, null, null, null); imageQuery.BeginExecute(_onImageQueryComplete, imageQuery); } // Handle the query callback. private void _onImageQueryComplete(IAsyncResult imageResults) { // Get the original query from the imageResults. DataServiceQuery<Bing.ImageResult> query = imageResults.AsyncState as DataServiceQuery<Bing.ImageResult>; var resultList = new List<string>(); foreach (var result in query.EndExecute(imageResults)) resultList.Add(result.MediaUrl); FindImageCompleted(this, resultList); } public event FindImageUrlsForEventHandler FindImageUrlsForCompleted; public delegate void FindImageUrlsForEventHandler(object sender, List<string> result); } }
例子
现在,让我们使用我提供给您的代码:
using Bing; using System; using System.Data.Services.Client; using System.Linq; using System.Net; namespace StackOverflow.Samples.BingSearch { public class MyPage { private void Button_Click_1(object sender, RoutedEventArgs e) { var finder = new Finder(); finder.FindImageUrlsForCompleted += finder_FindImageUrlsForCompleted; finder.FindImageUrlsFor("candy"); } void finder_FindImageUrlsForCompleted(object sender, List<string> result) { Deployment.Current.Dispatcher.BeginInvoke(() => { foreach (var s in result) MyTextBox.Text += s + "\n"; }); } } }
关于c# - 如何在 Windows Phone 中使用必应搜索 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122037/