快速入門:使用 Bing 圖像式搜尋 REST API 和 Java 來取得影像見解Quickstart: Get image insights using the Bing Visual Search REST API and Java

使用本快速入門進行您對 Bing 圖像式搜尋 API 的第一次呼叫,並檢視結果。Use this quickstart to make your first call to the Bing Visual Search API and view the results. 此 Java 應用程式會將影像上傳至 API,並顯示它傳回的資訊。This Java application uploads an image to the API and displays the information it returns. 雖然此應用程式是以 Java 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。Though this application is written in Java, the API is a RESTful Web service compatible with most programming languages.

上傳本機影像時,表單資料必須包含 Content-Disposition 標頭。When you upload a local image, the form data must include the Content-Disposition header. 您必須將其 name 參數設為 "image",而 filename 參數則可設為任何字串。You must set its name parameter to "image", and you can set the filename parameter to any string. 表單的內容包含影像的二進位資料。The contents of the form include the binary data of the image. 您可以上傳的影像大小上限為 1 MB。The maximum image size you can upload is 1 MB.

--boundary_1234-abcd
Content-Disposition: form-data; name="image"; filename="myimagefile.jpg"

ÿØÿà JFIF ÖÆ68g-¤CWŸþ29ÌÄøÖ‘º«™æ±èuZiÀ)"óÓß°Î= ØJ9á+*G¦...

--boundary_1234-abcd--

必要條件Prerequisites

您必須有具備 Bing 搜尋 API 存取權的認知服務 API 帳戶You must have a Cognitive Services API account with access to the Bing Search APIs. 在繼續進行之前,您需要在 S9 定價層上啟動訂用帳戶之後所提供的存取金鑰,如認知服務定價 - Bing 搜尋 API 中所示。Before continuing, You will need the access key provided after starting a subscription at S9 price tier as shown in Cognitive Services Pricing - Bing Search API.

若要在 Azure 入口網站中啟用訂用帳戶:To start a subscription in Azure portal:

  1. 在 Azure 入口網站頂端顯示 Search resources, services, and docs 的文字方塊中輸入 'BingSearchV7'。Enter 'BingSearchV7' in the text box at the top of the Azure portal that says Search resources, services, and docs.
  2. 在下拉式清單中的 Marketplace 下選取 Bing Search v7Under Marketplace in the drop-down list, select Bing Search v7.
  3. 輸入新資源的 NameEnter Name for the new resource.
  4. 選取 Pay-As-You-Go 訂用帳戶。Select Pay-As-You-Go subscription.
  5. 選取 S9 定價層。Select S9 pricing tier.
  6. 按一下 Enable 來啟用訂用帳戶。Click Enable to start the subscription.

建立專案並將其初始化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.util.*;
    import java.io.*;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    
    // HttpClient libraries
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    
  2. 為您的 API 端點、訂用帳戶金鑰以及您影像的路徑,建立變數:Create variables for your API endpoint, subscription key, and the path to your image:

    static String endpoint = "https://api.cognitive.microsoft.com/bing/v7.0/images/visualsearch";
    static String subscriptionKey = "your-key-here";
    static String imagePath = "path-to-your-image";
    

建立 JSON 剖析器Create the JSON parser

建立一個方法,讓來自 API 的 JSON 回應更容易使用 JsonParser 閱讀:Create a method to make the JSON response from the API more readable using JsonParser:

```java
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);
    }
```

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

  1. 在應用程式的 Main 方法中,使用 HttpClientBuilder.create().build(); 建立 HTTP 用戶端:In the main method of your application, create an HTTP client using HttpClientBuilder.create().build();:

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    
  2. 建立 HttpEntity 物件以將影像上傳至 API:Create an HttpEntity object to upload your image to the API:

    HttpEntity entity = MultipartEntityBuilder
        .create()
        .addBinaryBody("image", new File(imagePath))
        .build();
    
  3. 建立端點的 httpPost 物件,並設定要使用您訂用帳戶金鑰的標頭:Create an httpPost object with your endpoint, and set the header to use your subscription key:

    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
    httpPost.setEntity(entity);
    

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

  1. 使用 HttpClient.execute() 方法將要求傳送至 API,並且在 InputStream 物件中儲存回應:Use the HttpClient.execute() method to send a request to the API, and store the response in an InputStream object:

    HttpResponse response = httpClient.execute(httpPost);
    InputStream stream = response.getEntity().getContent();
    
  2. 儲存 JSON 字串並列印回應:Store the JSON string, and print the response:

String json = new Scanner(stream).useDelimiter("\\A").next();
System.out.println("\nJSON Response:\n");
System.out.println(prettify(json));

後續步驟Next steps