|
| 1 | +/*Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +Licensed under the MIT License.*/ |
| 3 | + |
| 4 | +import java.net.*; |
| 5 | +import java.util.*; |
| 6 | +import java.io.*; |
| 7 | +import javax.net.ssl.HttpsURLConnection; |
| 8 | + |
| 9 | +/* |
| 10 | + * Gson: https://github.com/google/gson |
| 11 | + * Maven info: |
| 12 | + * groupId: com.google.code.gson |
| 13 | + * artifactId: gson |
| 14 | + * version: 2.8.1 |
| 15 | + * |
| 16 | + * Once you have compiled or downloaded gson-2.8.1.jar, assuming you have placed it in the |
| 17 | + * same folder as this file (BingImageSearch.java), you can compile and run this program with the following steps: |
| 18 | + * 1. create three directories, named "bin", "src", and "lib" |
| 19 | + * 2. place this .java file in "src" |
| 20 | + * 3. download the latest gson .jar file online, and place it in the "lib" folder |
| 21 | + * 4. replace the subscriptionKey value with your valid Cognitive services subscription key |
| 22 | + * 5. run the following commands, replacing "lib/gson-2.8.5.jar" with your .jar file: |
| 23 | + * javac -d bin -sourcepath src -cp lib/gson-2.8.5.jar src/BingImageSearchv7Quickstart.java |
| 24 | + * java -cp bin;lib/gson-2.8.5.jar BingImageSearchv7Quickstart |
| 25 | + */ |
| 26 | +import com.google.gson.Gson; |
| 27 | +import com.google.gson.GsonBuilder; |
| 28 | +import com.google.gson.JsonObject; |
| 29 | +import com.google.gson.JsonParser; |
| 30 | +import com.google.gson.JsonArray; |
| 31 | + |
| 32 | +public class BingImageSearchv7Quickstart { |
| 33 | + |
| 34 | +// *********************************************** |
| 35 | +// *** Update or verify the following values. *** |
| 36 | +// ********************************************** |
| 37 | + |
| 38 | + // Replace the subscriptionKey string value with your valid subscription key. |
| 39 | + static String subscriptionKey = "enter key here"; |
| 40 | + |
| 41 | + // Verify the endpoint URI. At this writing, only one endpoint is used for Bing |
| 42 | + // search APIs. In the future, regional endpoints may be available. If you |
| 43 | + // encounter unexpected authorization errors, double-check this value against |
| 44 | + // the endpoint for your Bing Web search instance in your Azure dashboard. |
| 45 | + static String host = "https://api.cognitive.microsoft.com"; |
| 46 | + static String path = "/bing/v7.0/images/search"; |
| 47 | + |
| 48 | + static String searchTerm = "tropical ocean"; |
| 49 | + |
| 50 | + public static SearchResults SearchImages (String searchQuery) throws Exception { |
| 51 | + // construct URL of search request (endpoint + query string) |
| 52 | + URL url = new URL(host + path + "?q=" + URLEncoder.encode(searchQuery, "UTF-8")); |
| 53 | + HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(); |
| 54 | + connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey); |
| 55 | + |
| 56 | + // receive JSON body |
| 57 | + InputStream stream = connection.getInputStream(); |
| 58 | + String response = new Scanner(stream).useDelimiter("\\A").next(); |
| 59 | + |
| 60 | + // construct result object for return |
| 61 | + SearchResults results = new SearchResults(new HashMap<String, String>(), response); |
| 62 | + |
| 63 | + // extract Bing-related HTTP headers |
| 64 | + Map<String, List<String>> headers = connection.getHeaderFields(); |
| 65 | + for (String header : headers.keySet()) { |
| 66 | + if (header == null) continue; // may have null key |
| 67 | + if (header.startsWith("BingAPIs-") || header.startsWith("X-MSEdge-")) { |
| 68 | + results.relevantHeaders.put(header, headers.get(header).get(0)); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + stream.close(); |
| 73 | + return results; |
| 74 | + } |
| 75 | + |
| 76 | + // pretty-printer for JSON; uses GSON parser to parse and re-serialize |
| 77 | + public static String prettify(String json_text) { |
| 78 | + JsonParser parser = new JsonParser(); |
| 79 | + JsonObject json = parser.parse(json_text).getAsJsonObject(); |
| 80 | + Gson gson = new GsonBuilder().setPrettyPrinting().create(); |
| 81 | + return gson.toJson(json); |
| 82 | + } |
| 83 | + |
| 84 | + public static void main (String[] args) { |
| 85 | + if (subscriptionKey.length() != 32) { |
| 86 | + System.out.println("Invalid Bing Search API subscription key!"); |
| 87 | + System.out.println("Please paste yours into the source code."); |
| 88 | + System.exit(1); |
| 89 | + } |
| 90 | + |
| 91 | + try { |
| 92 | + System.out.println("Searching the Web for: " + searchTerm); |
| 93 | + |
| 94 | + SearchResults result = SearchImages(searchTerm); |
| 95 | + //uncomment this section to see the HTTP headers |
| 96 | + /* |
| 97 | + System.out.println("\nRelevant HTTP Headers:\n"); |
| 98 | + for (String header : result.relevantHeaders.keySet()) |
| 99 | + System.out.println(header + ": " + result.relevantHeaders.get(header)); |
| 100 | + */ |
| 101 | + |
| 102 | + System.out.println("\nJSON Response:\n"); |
| 103 | + //parse the jseon |
| 104 | + JsonParser parser = new JsonParser(); |
| 105 | + JsonObject json = parser.parse(result.jsonResponse).getAsJsonObject(); |
| 106 | + //get the first image result from the JSON object, along with the total |
| 107 | + //number of images returned by the Bing Image Search API. |
| 108 | + String total = json.get("totalEstimatedMatches").getAsString(); |
| 109 | + JsonArray results = json.getAsJsonArray("value"); |
| 110 | + JsonObject first_result = (JsonObject)results.get(0); |
| 111 | + String resultURL = first_result.get("thumbnailUrl").getAsString(); |
| 112 | + |
| 113 | + System.out.println("\nThe total number of images found: "+ total +"\n"); |
| 114 | + System.out.println("\nThe thumbnail URL to the first image search URL: "+ resultURL +"\n"); |
| 115 | + |
| 116 | + } |
| 117 | + catch (Exception e) { |
| 118 | + e.printStackTrace(System.out); |
| 119 | + System.exit(1); |
| 120 | + } |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +// Container class for search results encapsulates relevant headers and JSON data |
| 125 | +class SearchResults{ |
| 126 | + HashMap<String, String> relevantHeaders; |
| 127 | + String jsonResponse; |
| 128 | + SearchResults(HashMap<String, String> headers, String json) { |
| 129 | + relevantHeaders = headers; |
| 130 | + jsonResponse = json; |
| 131 | + } |
| 132 | +} |
0 commit comments