65.9K
CodeProject 正在变化。 阅读更多。
Home

Bing 本地商业搜索 API

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2019 年 1 月 24 日

CPOL

2分钟阅读

viewsIcon

4766

开始使用 Bing 本地商业搜索。

引言

必应本地商家搜索可以在指定的地理区域内查找商家。该 API 可以从任何能够发送 REST 请求的代码语言访问。请求查询指定商家名称和位置,例如 'q=auto repair in Olympia, WA'。可以使用圆形或方形的 地理边界,或者使用 X-Search-Location 头来设置搜索区域。results-by-category 选项可以使用调用者的反向 IP 位置或 GPS 坐标来返回各种类型业务的本地化结果。

结果包括商家的网站 URL 和显示文本、电话号码以及地理位置,包括:GPS 坐标、城市、街道地址。

背景

必应本地搜索端点扩展了必应搜索 API。

Using the Code

查找本地化商家代码分为两部分

  1. 构造并发送 REST 请求到端点:https://api.cognitive.microsoft.com/bing/v7.0/localbusinesses/search
  2. 解析 JSON 结果。

要向本地商家搜索端点发送 WebRequest,您需要一个可用的访问密钥,该密钥具有 认知服务 API 帐户,用于必应搜索 API。 免费试用足以进行测试。对于生产环境,在 Azure 门户中创建资源时,请选择 S10 级别。另请参阅 认知服务定价 - 必应搜索 API

以下代码构造一个请求,将其发送到端点并读取结果。目前,本地商家搜索仅支持英语美国市场。

   // Assign a valid access key.
   const string accessKey = "Your-Access-Key";

   const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/localbusinesses/search";   

   const string searchTerm = "auto repair in Olympia, WA";

   // Concatenate the uriBase and query for the request. 
   var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery) + mkt=en-us;

   // Create the request, and add the access key header.
   WebRequest request = HttpWebRequest.Create(uriQuery);
   request.Headers["Ocp-Apim-Subscription-Key"] = accessKey; 

   // Get the results.
   HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
   string json = new StreamReader(response.GetResponseStream()).ReadToEnd();

使用以下结构来包含请求和标头的结果。

  // Search results as JSON and relevant headers
  struct SearchResult
  {
     public String jsonResult;
     public Dictionary<String, String> relevantHeaders;
  }

使用以下方法解析 JSON 文本,该方法来自 Microsoft 文档

        /// <summary>
        /// Formats the given JSON string by adding line breaks and indents.
        /// </summary>
        /// <param name="json">The raw JSON string to format.</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;
            int offset = 0;
            int indentLength = 3;

            foreach (char ch in json)
            {
                switch (ch)
                {
                    case '"':
                        if (!ignore) quote = !quote;
                        break;
                    case '\'':
                        if (quote) ignore = !ignore;
                        break;
                }

                if (quote)
                    sb.Append(ch);
                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 (ch != ' ') sb.Append(ch);
                            break;
                    }
                }
            }

            return sb.ToString().Trim();
        }

在控制台应用程序中运行代码

完整的代码显示在以下块中

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace LocalBusinessSrchCshp
{
    class Program
    {
        // **********************************************
        // *** Update or verify the following values. ***
        // **********************************************

        // Replace the accessKey string value with your valid access key.
        const string accessKey = "Your-Access-Key";
        const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/localbusinesses/search";

        const string searchTerm = "auto repair in Olympia, WA";

        // Returns search results including relevant headers
        struct SearchResult
        {
            public String jsonResult;
            public Dictionary<String, String> relevantHeaders;
        }

        static void Main()
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Searching locally for: " + searchTerm);

            SearchResult result = BingLocalSearch(searchTerm, accessKey);

            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));

            Console.Write("\nPress Enter to exit ");
            Console.ReadLine();
        }

        /// <summary>
        /// Runs a Bing Local business search and returns the results as a SearchResult.
        /// </summary>
        static SearchResult BingLocalSearch(string searchQuery, string key)
        {
            // Construct the URI of the search request
            var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery) + "&mkt=en-us";

            // Run 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();
            searchResult.jsonResult = json;
            searchResult.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;
        }

        /// <summary>
        /// Formats the given JSON string by adding line breaks and indents.
        /// </summary>
        /// <param name="json">The raw JSON string to format.</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;
            int offset = 0;
            int indentLength = 3;

            foreach (char ch in json)
            {
                switch (ch)
                {
                    case '"':
                        if (!ignore) quote = !quote;
                        break;
                    case '\'':
                        if (quote) ignore = !ignore;
                        break;
                }

                if (quote)
                    sb.Append(ch);
                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 (ch != ' ') sb.Append(ch);
                            break;
                    }
                }
            }

            return sb.ToString().Trim();
        }
    }
}

使用反向 IP 和半径搜索

此方法使用 X-Search-Location 头和米为单位的半径来查找用户位置周围圆形区域内的商家,该位置由反向 IP 确定。对前面的代码进行两个小更改,如以下块所示。

首先,更改搜索词,省略位置

    //const string searchTerm = "auto repair in Olympia, WA";
    const string searchTerm = "auto repair";

然后,添加半径标头并分配一个值,在本例中为 18,000 米。

   // Run the Web request and get the response
   WebRequest request = HttpWebRequest.Create(uriQuery);
   request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
   request.Headers["re"] = "18,000m"; 

运行修改后的应用程序以获取结果。

使用经度/纬度搜索

指定搜索词,省略位置

   //const string searchTerm = "auto repair in Olympia, WA";
   const string searchTerm = "auto repair";

添加经度/纬度标头。

   // Run the Web request and get the response
   WebRequest request = HttpWebRequest.Create(uriQuery);
   request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
   request.Headers["long"] = "47.642065";
   request.Headers["lat"] = "-122.13061";

运行修改后的应用程序以获取结果。

历史

  • 版本 1.0.0
© . All rights reserved.