共用方式為


快速入門:使用 Java 呼叫 Bing 自定義搜尋端點

警告

在 2020 年 10 月 30 日,Bing 搜尋 API 從 Azure AI 服務移至 Bing 搜尋服務。 本文件僅供參考之用。 如需更新的檔,請參閱 Bing 搜尋 API 檔。 如需建立 Bing 搜尋新 Azure 資源的指示,請參閱 透過 Azure Marketplace 建立 Bing 搜尋資源

使用此快速入門瞭解如何向 Bing 自定義搜尋實例要求搜尋結果。 雖然此應用程式是以 Java 撰寫,但 Bing 自定義搜尋 API 是與大部分程式設計語言相容的 RESTful Web 服務。 此範例的原始程式碼可在 GitHub 取得。

先決條件

建立 Azure 資源

建立下列其中一個 Azure 資源,以開始使用 Bing 自定義搜尋 API。

Bing 自定義搜尋資源

  • 可透過 Azure 入口網站取得,直到您刪除資源為止。
  • 使用免費定價層來試用服務,稍後升級至生產環境的付費層。

多服務資源

  • 可透過 Azure 入口網站取得,直到您刪除資源為止。
  • 針對您的應用程式,跨多個 Azure AI 服務使用相同的金鑰和端點。

建立和初始化應用程式

  1. 在您慣用的 IDE 或編輯器中建立新的 Java 專案,並匯入下列連結庫:

    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Scanner;
    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;
    
  2. 建立名為 CustomSrchJava的類別,然後為您的訂用帳戶密鑰、自定義搜尋端點和搜尋實例的自定義組態標識元建立變數。 您可以在下列程式代碼中使用全域端點,或使用 Azure 入口網站中針對您的資源顯示的 自定義子域 端點。

    public class CustomSrchJava {
        static String host = "https://api.cognitive.microsoft.com";
        static String path = "/bingcustomsearch/v7.0/search";
        static String subscriptionKey = "YOUR-SUBSCRIPTION-KEY"; 
        static String customConfigId = "YOUR-CUSTOM-CONFIG-ID";
        static String searchTerm = "Microsoft";  
    ...
    
  3. 建立名為 SearchResults 的另一個類別,以包含 Bing 自定義搜尋實例的回應。

    class SearchResults {
        HashMap<String, String> relevantHeaders;
        String jsonResponse;
        SearchResults(HashMap<String, String> headers, String json) {
            relevantHeaders = headers;
            jsonResponse = json;
        }
    }
    
  4. 建立名為 prettify() 的函式,以格式化來自 Bing 自定義搜尋 API 的 JSON 回應。

        // pretty-printer for JSON; uses GSON parser to parse and re-serialize
        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);
        }
    

傳送和接收搜尋要求

  1. 建立名為 SearchWeb() 的函式,以傳送要求並傳 SearchResults 回 物件。 結合您的自定義組態標識碼、查詢和端點資訊,建立要求URL。 將訂用帳戶金鑰新增至 Ocp-Apim-Subscription-Key 標頭。

    public class CustomSrchJava {
    ...
        public static SearchResults SearchWeb (String searchQuery) throws Exception {
            // construct the URL for your search request (endpoint + query string)
            URL url = new URL(host + path + "?q=" +  URLEncoder.encode(searchTerm, "UTF-8") + "&CustomConfig=" + customConfigId);
            HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
            connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
    ...
    
  2. 建立數據流,並將 JSON 回應儲存在 物件中 SearchResults

    public class CustomSrchJava {
    ...
        public static SearchResults SearchWeb (String searchQuery) throws Exception {
            ...
            // receive the JSON body
            InputStream stream = connection.getInputStream();
            String response = new Scanner(stream).useDelimiter("\\A").next();
    
            // construct result object for return
            SearchResults results = new SearchResults(new HashMap<String, String>(), response);
    
            stream.close();
            return results;
        }
    
  3. 列印 JSON 回應。

    System.out.println("\nJSON Response:\n");
    System.out.println(prettify(result.jsonResponse));
    
  4. 執行程式。

後續步驟