快速入門:使用 Bing Web 搜尋 REST API 和 Java 來搜尋 WebQuickstart: Search the web using the Bing Web Search REST API and Java

使用本快速入門進行對 Bing Web 搜尋 API 第一次的呼叫,並接收 JSON 回應。Use this quickstart to make your first call to the Bing Web Search API and receive the JSON response. 這個 Java 應用程式會將搜尋要求傳送給 API,並顯示回應。This Java application sends a search request to the API, and shows the response. 雖然此應用程式是以 Java 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in Java, the API is a RESTful Web service compatible with most programming languages.

必要條件Prerequisites

以下是執行本快速入門之前的幾個必備項目:Here are a few things that you'll need before running this quickstart:

本快速入門需要 Azure 認知服務帳戶及 Bing 搜尋 API。This quickstart requires an Azure Cognitive Services account with Bing Search APIs. 如果您還沒有帳戶,可以使用免費試用來取得訂用帳戶金鑰。If you don't have an account, you can use the free trial to get a subscription key.

建立專案並匯入相依性Create a project and import dependencies

在您慣用的 IDE 或編輯器中建立新的 Java 專案,並匯入下列程式庫。Create a new Java project in your favorite IDE or editor and import the following libraries. 需要 Gson 才能將 Java 物件轉換成 JSON。Gson is required to convert Java Objects into JSON.

import java.net.*;
import java.util.*;
import java.io.*;
import javax.net.ssl.HttpsURLConnection;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

在 Maven POM 檔案中宣告 GsonDeclare Gson in the Maven POM file

如果您使用 Maven,請在 POM.xml 中宣告 Gson。If you're using Maven, declare Gson in the POM.xml. 如果您已在本機安裝 Gson,請略過此步驟。Skip this step if you've installed Gson locally.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

宣告 BingWebSearch 類別Declare the BingWebSearch class

宣告 BingWebSearch 類別。Declare the BingWebSearch class. 其中包含我們在此快速入門中檢閱的大部分程式碼,包括 main 方法。It will include most of the code we review in this quickstart including the main method.

public class BingWebSearch {

// The code in the following sections goes here.

}

定義變數Define variables

此程式碼會設定 subscriptionKeyhostpathsearchTermThis code sets the subscriptionKey, host, path, and searchTerm. 請確認端點正確,並將 subscriptionKey 值換成您的 Azure 帳戶中有效的訂用帳戶金鑰。Confirm that the endpoint is correct and replace the subscriptionKey value with a valid subscription key from your Azure account. 請自行取代 searchTerm 的值來自訂搜尋查詢。Feel free to customize the search query by replacing the value for searchTerm. 請記得將此程式碼新增至 BingWebSearch 類別,如先前所述。Remember to add this code to the BingWebSearch class as noted above.

// Enter a valid subscription key.
static String subscriptionKey = "enter key here";

/*
 * If you encounter unexpected authorization errors, double-check these values
 * against the endpoint for your Bing Web search instance in your Azure
 * dashboard.
 */
static String host = "https://api.cognitive.microsoft.com";
static String path = "/bing/v7.0/search";
static String searchTerm = "Microsoft Cognitive Services";

建構要求Construct a request

此方法 (位於 BingWebSearch 類別中) 會建構 url、接收和剖析回應,並擷取 Bing 相關的 HTTP 標頭。This method, which lives in the BingWebSearch class, constructs the url, receives and parses the response, and extracts Bing-related HTTP headers.

public static SearchResults SearchWeb (String searchQuery) throws Exception {
    // Construct the URL.
    URL url = new URL(host + path + "?q=" +  URLEncoder.encode(searchQuery, "UTF-8"));

    // Open the connection.
    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
    connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);

    // Receive the JSON response body.
    InputStream stream = connection.getInputStream();
    String response = new Scanner(stream).useDelimiter("\\A").next();

    // Construct the result object.
    SearchResults results = new SearchResults(new HashMap<String, String>(), response);

    // Extract Bing-related HTTP headers.
    Map<String, List<String>> headers = connection.getHeaderFields();
    for (String header : headers.keySet()) {
        if (header == null) continue;      // may have null key
        if (header.startsWith("BingAPIs-") || header.startsWith("X-MSEdge-")){
            results.relevantHeaders.put(header, headers.get(header).get(0));
        }
    }
    stream.close();
    return results;
}

處理回應Handle the response

使用 Gson 來剖析和重新序列化回應。Use Gson to parse and reserialize the response.

public static String prettify(String json_text) {
    JsonParser parser = new JsonParser();
    JsonObject json = parser.parse(json_text).getAsJsonObject();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    return gson.toJson(json);
}

宣告 main 方法Declare the main method

這是必要方法,也是程式啟動時叫用的第一個方法。This method is required and is the first method invoked when the program is started. 在此應用程式中,此方法包含的程式碼會驗證 subscriptionKey、提出要求,並列印 JSON 回應。In this application, it includes code that validates the subscriptionKey, makes a request, and prints the JSON response.

public static void main (String[] args) {
    // Confirm the subscriptionKey is valid.
    if (subscriptionKey.length() != 32) {
        System.out.println("Invalid Bing Search API subscription key!");
        System.out.println("Please paste yours into the source code.");
        System.exit(1);
    }

    // Call the SearchWeb method and print the response.
    try {
        System.out.println("Searching the Web for: " + searchTerm);
        SearchResults result = SearchWeb(searchTerm);
        System.out.println("\nRelevant HTTP Headers:\n");
        for (String header : result.relevantHeaders.keySet())
        System.out.println(header + ": " + result.relevantHeaders.get(header));
        System.out.println("\nJSON Response:\n");
        System.out.println(prettify(result.jsonResponse));
    }
    catch (Exception e) {
        e.printStackTrace(System.out);
        System.exit(1);
    }
}

建立搜尋結果的容器類別Create a container class for search results

SearchResults 容器類別位於 BingWebSearch 類別外部。The SearchResults container class is outside of the BingWebSearch class. 其中包含回應的相關標頭和 JSON 資料。It includes relevant headers and JSON data for the response.

class SearchResults{
    HashMap<String, String> relevantHeaders;
    String jsonResponse;
    SearchResults(HashMap<String, String> headers, String json) {
        relevantHeaders = headers;
        jsonResponse = json;
    }
}

組合在一起Put it all together

最後一步就是編譯您的程式碼並執行!The last step is to compile your code and run it! 命令如下:Here are the commands:

javac BingWebSearch.java -classpath ./gson-2.8.5.jar -encoding UTF-8
java -cp ./gson-2.8.5.jar BingWebSearch

如果想要將您的程式碼與我們的程式碼做比較,GitHub 上提供程式碼範例 (英文)。If you'd like to compare your code with ours, sample code is available on GitHub.

範例回應Sample response

來自 Bing Web 搜尋 API 的回應會以 JSON 格式傳回。Responses from the Bing Web Search API are returned as JSON. 本範例回應已截斷而只顯示單一結果。This sample response has been truncated to show a single result.

{
  "_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 API",
            "url": "https://azure.microsoft.com/services/cognitive-services/face/",
            "snippet": "Add facial recognition to your applications to detect, identify, and verify faces using a Face API from Microsoft Azure. ... Cognitive Services; Face API;"
          },
          {
            "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/services/cognitive-services/computer-vision/",
            "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"
          }
        }
      ]
    }
  }
}

後續步驟Next steps

另請參閱See also