快速入门:使用 Java 调用必应自定义搜索终结点

警告

2020 年 10 月 30 日,必应搜索 API 从 Azure AI 服务迁移到必应搜索服务。 本文档仅供参考。 有关更新的文档,请参阅必应搜索 API 文档。 关于为必应搜索创建新的 Azure 资源的说明,请参阅通过 Azure 市场创建必应搜索资源

使用此快速入门了解如何从必应自定义搜索实例请求搜索结果。 虽然此应用程序是以 Java 编写的,但必应自定义搜索 API 是一种 RESTful Web 服务,与大多数编程语言兼容。 该示例的源代码可在 GitHub 上获得。

先决条件

创建 Azure 资源

通过创建以下 Azure 资源之一开始使用必应自定义搜索 API。

必应自定义搜索资源

  • 在删除资源前,可通过 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 的类,然后为订阅密钥、自定义搜索终结点和搜索实例的自定义配置 ID 创建变量。 你可以使用以下代码中的全局终结点,或者使用资源的 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 的类,用于存储来自必应自定义搜索实例的响应。

    class SearchResults {
        HashMap<String, String> relevantHeaders;
        String jsonResponse;
        SearchResults(HashMap<String, String> headers, String json) {
            relevantHeaders = headers;
            jsonResponse = json;
        }
    }
    
  4. 创建名为 prettify() 的函数,用于设置来自必应自定义搜索 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 对象。 通过合并自定义配置 ID、查询和终结点信息,创建请求 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. 创建流并存储 SearchResults 对象中的 JSON 响应。

    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. 运行该程序。

后续步骤