/*Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.*/ import java.net.*; import java.util.*; import java.io.*; import javax.net.ssl.HttpsURLConnection; /* * Gson: https://github.com/google/gson * Maven info: * groupId: com.google.code.gson * artifactId: gson * version: 2.8.1 * * Once you have compiled or downloaded gson-2.8.1.jar, assuming you have placed it in the * same folder as this file (BingWebSearch.java), you can compile and run this program at * the command line as follows. * * javac BingWebSearch.java -classpath .;gson-2.8.1.jar -encoding UTF-8 * java -cp .;gson-2.8.1.jar BingWebSearch */ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class BingWebSearch { // *********************************************** // *** Update or verify the following values. *** // ********************************************** // Add your Bing Search V7 subscription key to your environment variables. static String subscriptionKey = System.getenv("BING_SEARCH_V7_SUBSCRIPTION_KEY"); // Add your Bing Search V7 endpoint to your environment variables. static String host = System.getenv("BING_SEARCH_V7_ENDPOINT"); static String path = "/bing/v7.0/search"; static String searchTerm = "Microsoft Cognitive Services"; public static SearchResults SearchWeb (String searchQuery) throws Exception { // construct URL of search request (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); // 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(), response); // extract Bing-related HTTP headers Map> 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)); } } stream.close(); return results; } // pretty-printer for JSON; uses GSON parser to parse and re-serialize 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); } public static void main (String[] args) { if (subscriptionKey.length() != 32) { System.out.println("Invalid Bing Search API subscription key!"); System.out.println("Please paste yours into the source code."); System.exit(1); } try { System.out.println("Searching the Web for: " + searchTerm); SearchResults result = SearchWeb(searchTerm); System.out.println("\nRelevant HTTP Headers:\n"); for (String header : result.relevantHeaders.keySet()) System.out.println(header + ": " + result.relevantHeaders.get(header)); System.out.println("\nJSON Response:\n"); System.out.println(prettify(result.jsonResponse)); } catch (Exception e) { e.printStackTrace(System.out); System.exit(1); } } } // Container class for search results encapsulates relevant headers and JSON data class SearchResults{ HashMap relevantHeaders; String jsonResponse; SearchResults(HashMap headers, String json) { relevantHeaders = headers; jsonResponse = json; } }