快速入門:使用 Bing 影像搜尋 REST API 和 Java 來搜尋影像Quickstart: Search for images using the Bing Image Search REST API and Java

使用本快速入門,開始將搜尋要求傳送至 Bing 影像搜尋 API。Use this quickstart to start sending search requests to the Bing Image Search API. 這個 Java 應用程式會將搜尋查詢傳送至 API,並顯示結果中第一個影像的 URL。This Java application sends a search query to the API, and displays the URL of the first image in the results. 雖然此應用程式是以 Java 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in Java, the API is a RESTful web service compatible with most programming languages.

此範例的原始程式碼可從 GitHub 取得,其中含有其他錯誤處理和註釋。The source code for this sample is available on GitHub with additional error handling and annotations.

必要條件Prerequisites

您必須有具備 Bing 搜尋 API 存取權的認知服務 API 帳戶You must have a Cognitive Services API account with access to the Bing Search APIs. 如果您沒有 Azure 訂用帳戶,可以建立免費帳戶If you don't have an Azure subscription, you can create an account for free. 繼續之前,您需要有啟動免費試用版後所提供的存取金鑰,或是從 Azure 儀表板中取得的付費訂用帳戶金鑰。Before continuing, You will need the access key provided after activating your free trial, or a paid subscription key from your Azure dashboard.

建立專案並將其初始化Create and initialize a project

  1. 在您最愛的 IDE 或編輯器中建立新的 Java 專案,並匯入下列程式庫。Create a new Java project in your favorite IDE or editor, and import the following libraries.

    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;
    
  2. 建立適用於 API 端點、您訂用帳戶金鑰及搜尋字詞的變數。Create variables for the API endpoint, your subscription key, and search term.

    static String subscriptionKey = "enter key here";
    static String host = "https://api.cognitive.microsoft.com";
    static String path = "/bing/v7.0/images/search";
    static String searchTerm = "tropical ocean";
    

建構搜尋要求和查詢Construct the search request and query

  1. 使用上一個步驟中的變數來製作適用於 API 要求的搜尋 URL 格式。Use the variables from the last step to format a search URL for the API request. 搜尋字詞必須先進行 URL 編碼,再附加至要求。The search term must be URL-encoded before being appended to the request.

    // construct the search request URL (in the form of endpoint + query string)
    URL url = new URL(host + path + "?q=" +  URLEncoder.encode(searchQuery, "UTF-8"));
    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
    connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
    

接收及處理 JSON 回應Receive and process the JSON response

  1. 接收來自「Bing 影像搜尋 API」的 JSON 回應,並建構結果物件。Receive the JSON response from the Bing Image Search API, and construct the result object.

    // receive 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);
    
  2. 將 Bing 相關的 HTTP 標頭與 JSON 本文分開Separate the Bing-related HTTP headers from the JSON body

    // 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));
        }
    }
    
  3. 關閉資料流並剖析回應。Close the stream, and parse the response. 取得所傳回搜尋結果的總數,以及第一個影像結果的縮圖 URL。Get the total number of returned search results, and the thumbnail url to the first image result.

    stream.close();
    JsonParser parser = new JsonParser();
    JsonObject json = parser.parse(result.jsonResponse).getAsJsonObject();
    //get the first image result from the JSON object, along with the total
    //number of images returned by the Bing Image Search API.
    String total = json.get("totalEstimatedMatches").getAsString();
    JsonArray results = json.getAsJsonArray("value");
    JsonObject first_result = (JsonObject)results.get(0);
    String resultURL = first_result.get("thumbnailUrl").getAsString();
    

範例 JSON 回應Example JSON response

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

{
"_type":"Images",
"instrumentation":{
    "_type":"ResponseInstrumentation"
},
"readLink":"images\/search?q=tropical ocean",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=tropical ocean&FORM=OIIARP",
"totalEstimatedMatches":842,
"nextOffset":47,
"value":[
    {
        "webSearchUrl":"https:\/\/www.bing.com\/images\/search?view=detailv2&FORM=OIIRPO&q=tropical+ocean&id=8607ACDACB243BDEA7E1EF78127DA931E680E3A5&simid=608027248313960152",
        "name":"My Life in the Ocean | The greatest WordPress.com site in ...",
        "thumbnailUrl":"https:\/\/tse3.mm.bing.net\/th?id=OIP.fmwSKKmKpmZtJiBDps1kLAHaEo&pid=Api",
        "datePublished":"2017-11-03T08:51:00.0000000Z",
        "contentUrl":"https:\/\/mylifeintheocean.files.wordpress.com\/2012\/11\/tropical-ocean-wallpaper-1920x12003.jpg",
        "hostPageUrl":"https:\/\/mylifeintheocean.wordpress.com\/",
        "contentSize":"897388 B",
        "encodingFormat":"jpeg",
        "hostPageDisplayUrl":"https:\/\/mylifeintheocean.wordpress.com",
        "width":1920,
        "height":1200,
        "thumbnail":{
        "width":474,
        "height":296
        },
        "imageInsightsToken":"ccid_fmwSKKmK*mid_8607ACDACB243BDEA7E1EF78127DA931E680E3A5*simid_608027248313960152*thid_OIP.fmwSKKmKpmZtJiBDps1kLAHaEo",
        "insightsMetadata":{
        "recipeSourcesCount":0,
        "bestRepresentativeQuery":{
            "text":"Tropical Beaches Desktop Wallpaper",
            "displayText":"Tropical Beaches Desktop Wallpaper",
            "webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=Tropical+Beaches+Desktop+Wallpaper&id=8607ACDACB243BDEA7E1EF78127DA931E680E3A5&FORM=IDBQDM"
        },
        "pagesIncludingCount":115,
        "availableSizesCount":44
        },
        "imageId":"8607ACDACB243BDEA7E1EF78127DA931E680E3A5",
        "accentColor":"0050B2"
    }]
}

後續步驟Next steps

另請參閱See also