1- /* Copyright (c) Microsoft Corporation. All rights reserved.
2- Licensed under the MIT License.*/
1+ // Copyright (c) Microsoft Corporation. All rights reserved.
2+ // Licensed under the MIT License.
33
44import java .net .*;
55import java .util .*;
66import java .io .*;
77import javax .net .ssl .HttpsURLConnection ;
8+ import com .google .gson .Gson ;
9+ import com .google .gson .GsonBuilder ;
10+ import com .google .gson .JsonObject ;
11+ import com .google .gson .JsonParser ;
812
913/*
1014 * Gson: https://github.com/google/gson
1115 * 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 at
18- * the command line as follows.
16+ * groupId: com.google.code.gson
17+ * artifactId: gson
18+ * version: x.x.x
1919 *
20- * javac BingImageSearch.java -classpath .;gson-2.8.1.jar -encoding UTF-8
21- * java -cp .;gson-2.8.1.jar BingImageSearch
20+ * Compile and run from the command line:
21+ * javac BingImageSearch.java -classpath .;gson-2.8.6.jar -encoding UTF-8
22+ * java -cp .;gson-2.8.6.jar BingImageSearch
2223 */
23- import com .google .gson .Gson ;
24- import com .google .gson .GsonBuilder ;
25- import com .google .gson .JsonObject ;
26- import com .google .gson .JsonParser ;
2724
2825public class BingImageSearch {
29-
30- // ***********************************************
31- // *** Update or verify the following values. ***
32- // **********************************************
33-
3426 // Add your Bing Search V7 subscription key to your environment variables.
3527 static String subscriptionKey = System .getenv ("BING_SEARCH_V7_SUBSCRIPTION_KEY" );
3628 // Add your Bing Search V7 endpoint to your environment variables.
37- static String host = System .getenv ("BING_SEARCH_V7_ENDPOINT" );
38- static String path = "/bing/v7.0/images/search" ;
29+ static String endpoint = System .getenv ("BING_SEARCH_V7_ENDPOINT" ) + "/bing/v7.0/images/search" ;
3930
4031 static String searchTerm = "puppies" ;
4132
33+ public static void main (String [] args ) {
34+ try {
35+ System .out .println ("Searching the Web for: " + searchTerm );
36+
37+ SearchResults result = SearchImages (searchTerm );
38+
39+ System .out .println ("\n Relevant HTTP Headers:\n " );
40+ for (String header : result .relevantHeaders .keySet ())
41+ System .out .println (header + ": " + result .relevantHeaders .get (header ));
42+
43+ System .out .println ("\n JSON Response:\n " );
44+ System .out .println (prettify (result .jsonResponse ));
45+ } catch (Exception e ) {
46+ e .printStackTrace (System .out );
47+ System .exit (1 );
48+ }
49+ }
50+
4251 public static SearchResults SearchImages (String searchQuery ) throws Exception {
43- // construct URL of search request (endpoint + query string)
44- URL url = new URL (host + path + "?q=" + URLEncoder .encode (searchQuery , "UTF-8" ));
52+ // Construct URL of search request (endpoint + query string)
53+ URL url = new URL (endpoint + "?q=" + URLEncoder .encode (searchQuery , "UTF-8" ));
4554 HttpsURLConnection connection = (HttpsURLConnection )url .openConnection ();
4655 connection .setRequestProperty ("Ocp-Apim-Subscription-Key" , subscriptionKey );
4756
48- // receive JSON body
57+ // Receive JSON body
4958 InputStream stream = connection .getInputStream ();
50- String response = new Scanner (stream ).useDelimiter ("\\ A" ).next ();
59+ Scanner scanner = new Scanner (stream );
60+ String response = scanner .useDelimiter ("\\ A" ).next ();
5161
52- // construct result object for return
62+ // Construct result object for return
5363 SearchResults results = new SearchResults (new HashMap <String , String >(), response );
5464
55- // extract Bing-related HTTP headers
65+ // Extract Bing-related HTTP headers
5666 Map <String , List <String >> headers = connection .getHeaderFields ();
5767 for (String header : headers .keySet ()) {
5868 if (header == null ) continue ; // may have null key
@@ -61,42 +71,18 @@ public static SearchResults SearchImages (String searchQuery) throws Exception {
6171 }
6272 }
6373
74+ scanner .close ();
6475 stream .close ();
76+
6577 return results ;
6678 }
6779
6880 // pretty-printer for JSON; uses GSON parser to parse and re-serialize
6981 public static String prettify (String json_text ) {
70- JsonParser parser = new JsonParser ();
71- JsonObject json = parser .parse (json_text ).getAsJsonObject ();
82+ JsonObject json = JsonParser .parseString (json_text ).getAsJsonObject ();
7283 Gson gson = new GsonBuilder ().setPrettyPrinting ().create ();
7384 return gson .toJson (json );
7485 }
75-
76- public static void main (String [] args ) {
77- if (subscriptionKey .length () != 32 ) {
78- System .out .println ("Invalid Bing Search API subscription key!" );
79- System .out .println ("Please paste yours into the source code." );
80- System .exit (1 );
81- }
82-
83- try {
84- System .out .println ("Searching the Web for: " + searchTerm );
85-
86- SearchResults result = SearchImages (searchTerm );
87-
88- System .out .println ("\n Relevant HTTP Headers:\n " );
89- for (String header : result .relevantHeaders .keySet ())
90- System .out .println (header + ": " + result .relevantHeaders .get (header ));
91-
92- System .out .println ("\n JSON Response:\n " );
93- System .out .println (prettify (result .jsonResponse ));
94- }
95- catch (Exception e ) {
96- e .printStackTrace (System .out );
97- System .exit (1 );
98- }
99- }
10086}
10187
10288// Container class for search results encapsulates relevant headers and JSON data
0 commit comments