概述:通过bing的图片搜索引擎,开发自己的图片搜索应用程序。bing的图片搜索接口是收费的,但是初次注册使用,key可以免费试用30天
程序运行效果如下
一,代码如下
static SearchResult BingImageSearch(string searchQuery)
{
// Construct the URI of the search request
var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);
// Perform the Web request and get the 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 result object for return
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格式的搜索结果
二、点击搜索的时候
private void Button_Click(object sender, RoutedEventArgs e)
{
searchInfo.List.Clear();
string searchTerm = searchInfo.SearchTerm;
SearchResult result = BingImageSearch(searchTerm);
JObject jo = (JObject)JsonConvert.DeserializeObject(result.jsonResult);
IJEnumerable<JToken> values = jo["value"]; ;
foreach (JToken jk in values)
{
string imageUrl = jk["contentUrl"].ToString();
string imageTitle = jk["name"].ToString();
SearchItemResult sr = new SearchItemResult();
sr.Url = imageUrl;
sr.Title = imageTitle;
searchInfo.List.Add(sr);
}
把搜索结果添加到list里面。
}
在这不多说了,大家想看源码,可以直接到这个地址下载:http://download.csdn.net/download/soft_123456/10113322
谢谢!有任何问题可以给我留言。尽量在最短的时间内回复大家。