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// <imports>
44import javax .net .ssl .HttpsURLConnection ;
55import java .io .InputStream ;
1616import com .google .gson .JsonParser ;
1717// </imports>
1818
19- public class BingCustomSearchv7 {
19+ /**
20+ * This sample uses BingCustomSearch to do a web search with a text query and
21+ * return custom-designed results.
22+ *
23+ * Add the Bing Custom Search key, endpoint, and custom configuration ID to your
24+ * environment variables.
25+ *
26+ * Include the Gson library jar in your project folder:
27+ * https://github.com/google/gson
28+ *
29+ * To compile/run from command line:
30+ * javac BingCustomSearch.java -cp .;gson-2.8.6.jar
31+ * java -cp .;gson-2.8.6.jar BingCustomSearch
32+ */
2033
34+ public class BingCustomSearch {
2135 // <vars>
22- // Add your Bing Custom Search endpoint and key to your environment variables.
23- // Your endpoint will have the form:
24- // https://<your-custom-subdomain>.cognitiveservices.azure.com/bingcustomsearch/v7.0
25- static String host = System .getenv ("BING_CUSTOM_SEARCH_ENDPOINT" );
36+ // Add your Bing Custom Search subscription key and endpoint to your environment variables.
37+ // Example endpoint: https://<your-custom-subdomain>.cognitiveservices.azure.com
2638 static String subscriptionKey = System .getenv ("BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY" );
39+ static String endpoint = System .getenv ("BING_CUSTOM_SEARCH_ENDPOINT" ) + "/bingcustomsearch/v7.0/search" ;
2740
28- static String path = "/search" ;
29- static String customConfigId = "YOUR-CUSTOM-CONFIG-ID" ; //you can also use "1"
30- static String searchTerm = "Microsoft" ; // Replace with search term specific to your defined sources.
41+ static String customConfigId = System .getenv ("BING_CUSTOM_CONFIG" ); //you can also use "1"
42+ static String searchTerm = "Microsoft" ; // Replace with another search term, if you'd like.
3143 // </vars>
44+
45+ // <main>
46+ public static void main (String [] args ) {
47+ try {
48+ System .out .println ("Searching the Web for: " + searchTerm );
49+
50+ SearchResults result = SearchWeb (searchTerm );
51+
52+ System .out .println ("\n Relevant HTTP Headers:\n " );
53+ for (String header : result .relevantHeaders .keySet ())
54+ System .out .println (header + ": " + result .relevantHeaders .get (header ));
55+
56+ System .out .println ("\n JSON Response:\n " );
57+ System .out .println (prettify (result .jsonResponse ));
58+ }
59+ catch (Exception e ) {
60+ e .printStackTrace (System .out );
61+ System .exit (1 );
62+ }
63+ }
64+ // </main>
65+
3266 // <searchWeb>
3367 public static SearchResults SearchWeb (String searchQuery ) throws Exception {
34- // construct URL of search request (endpoint + query string)
35- URL url = new URL (host + path + "?q=" + URLEncoder .encode (searchTerm , "UTF-8" ) + "&CustomConfig=" + customConfigId );
68+ // Construct URL of search request (endpoint + query string)
69+ URL url = new URL (endpoint + "?q=" + URLEncoder .encode (searchTerm , "UTF-8" ) + "&CustomConfig=" + customConfigId );
3670 HttpsURLConnection connection = (HttpsURLConnection )url .openConnection ();
3771 connection .setRequestProperty ("Ocp-Apim-Subscription-Key" , subscriptionKey );
3872
39- // receive JSON body
73+ // Receive JSON body
4074 InputStream stream = connection .getInputStream ();
41- String response = new Scanner (stream ).useDelimiter ("\\ A" ).next ();
75+ Scanner scanner = new Scanner (stream );
76+ String response = scanner .useDelimiter ("\\ A" ).next ();
4277
43- // construct result object for return
78+ // Construct result object for return
4479 SearchResults results = new SearchResults (new HashMap <String , String >(), response );
4580
46- // extract Bing-related HTTP headers
81+ // Extract Bing-related HTTP headers
4782 Map <String , List <String >> headers = connection .getHeaderFields ();
4883 for (String header : headers .keySet ()) {
4984 if (header == null ) continue ; // may have null key
5085 if (header .startsWith ("BingAPIs-" ) || header .startsWith ("X-MSEdge-" )) {
5186 results .relevantHeaders .put (header , headers .get (header ).get (0 ));
5287 }
5388 }
54-
55- stream .close ();
89+ scanner .close ();
5690 return results ;
5791 }
5892 // </searchWeb>
93+
5994 // <prettify>
60- // pretty-printer for JSON; uses GSON parser to parse and re-serialize
61- public static String prettify (String json_text ) {
62- JsonParser parser = new JsonParser ();
63- JsonObject json = parser .parse (json_text ).getAsJsonObject ();
95+ // Pretty-printer for JSON; uses GSON parser to parse and re-serialize
96+ public static String prettify (String jsonText ) {
97+ JsonObject json = JsonParser .parseString (jsonText ).getAsJsonObject ();
6498 Gson gson = new GsonBuilder ().setPrettyPrinting ().create ();
6599 return gson .toJson (json );
66100 }
67101 // </prettify>
68- // <main>
69- public static void main (String [] args ) {
70- if (subscriptionKey .length () != 32 ) {
71- System .out .println ("Invalid Bing Search API subscription key!" );
72- System .out .println ("Please paste yours into the source code." );
73- System .exit (1 );
74- }
75-
76- try {
77- System .out .println ("Searching the Web for: " + searchTerm );
78-
79- SearchResults result = SearchWeb (searchTerm );
80-
81- System .out .println ("\n Relevant HTTP Headers:\n " );
82- for (String header : result .relevantHeaders .keySet ())
83- System .out .println (header + ": " + result .relevantHeaders .get (header ));
84-
85- System .out .println ("\n JSON Response:\n " );
86- System .out .println (prettify (result .jsonResponse ));
87- }
88- catch (Exception e ) {
89- e .printStackTrace (System .out );
90- System .exit (1 );
91- }
92- }
93- // </main>
94102}
95103
96104// <searchResultsClass>
97- // put this in a seperate .java file.
98- import java .util .HashMap ;
99-
100105// Container class for search results encapsulates relevant headers and JSON data
101106class SearchResults {
102107 HashMap <String , String > relevantHeaders ;
@@ -105,7 +110,5 @@ class SearchResults{
105110 relevantHeaders = headers ;
106111 jsonResponse = json ;
107112 }
108-
109113}
110114// </searchResultsClass>
111-
0 commit comments