Skip to content

Commit 608eebe

Browse files
authored
Updated sample, replaced deprecated code
1 parent c2f0196 commit 608eebe

File tree

1 file changed

+46
-58
lines changed

1 file changed

+46
-58
lines changed

java/Search/BingWebSearchv7.java

Lines changed: 46 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,103 +1,91 @@
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

44
import java.net.*;
55
import java.util.*;
66
import java.io.*;
77
import javax.net.ssl.HttpsURLConnection;
88

9-
/*
9+
import com.google.gson.Gson;
10+
import com.google.gson.GsonBuilder;
11+
import com.google.gson.JsonObject;
12+
import com.google.gson.JsonParser;
13+
14+
/**
15+
* This sample uses the Bing Web Search API with a text query to return relevant results from the web.
16+
*
17+
* Include the Gson jar library with your project:
1018
* Gson: https://github.com/google/gson
19+
*
1120
* Maven info:
1221
* groupId: com.google.code.gson
1322
* 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 (BingWebSearch.java), you can compile and run this program at
18-
* the command line as follows.
23+
* version: 2.8.6
1924
*
20-
* javac BingWebSearch.java -classpath .;gson-2.8.1.jar -encoding UTF-8
21-
* java -cp .;gson-2.8.1.jar BingWebSearch
25+
* Compile and run from the command line (change Gson version if needed):
26+
* javac BingWebSearch.java -cp .;gson-2.8.6.jar -encoding UTF-8
27+
* java -cp .;gson-2.8.6.jar BingWebSearch
2228
*/
23-
import com.google.gson.Gson;
24-
import com.google.gson.GsonBuilder;
25-
import com.google.gson.JsonObject;
26-
import com.google.gson.JsonParser;
27-
2829
public class BingWebSearch {
2930

30-
// ***********************************************
31-
// *** Update or verify the following values. ***
32-
// **********************************************
33-
3431
// Add your Bing Search V7 subscription key to your environment variables.
3532
static String subscriptionKey = System.getenv("BING_SEARCH_V7_SUBSCRIPTION_KEY");
33+
static String endpoint = System.getenv("BING_SEARCH_V7_ENDPOINT") + "/bing/v7.0/search";
34+
// Add your own search terms, if desired.
35+
static String searchTerm = "Microsoft Cognitive Services";
3636

37-
// Add your Bing Search V7 endpoint to your environment variables.
38-
static String host = System.getenv("BING_SEARCH_V7_ENDPOINT");
39-
static String path = "/bing/v7.0/search";
37+
public static void main(String[] args) {
38+
try {
39+
System.out.println("Searching the Web for: " + searchTerm);
4040

41-
static String searchTerm = "Microsoft Cognitive Services";
41+
SearchResults result = SearchWeb(searchTerm);
42+
43+
System.out.println("\nRelevant HTTP Headers:\n");
44+
for (String header : result.relevantHeaders.keySet())
45+
System.out.println(header + ": " + result.relevantHeaders.get(header));
46+
47+
System.out.println("\nJSON Response:\n");
48+
System.out.println(prettify(result.jsonResponse));
49+
} catch (Exception e) {
50+
e.printStackTrace(System.out);
51+
System.exit(1);
52+
}
53+
}
4254

4355
public static SearchResults SearchWeb (String searchQuery) throws Exception {
44-
// construct URL of search request (endpoint + query string)
45-
URL url = new URL(host + path + "?q=" + URLEncoder.encode(searchQuery, "UTF-8"));
56+
// Construct URL of search request (endpoint + query string)
57+
URL url = new URL(endpoint + "?q=" + URLEncoder.encode(searchQuery, "UTF-8"));
4658
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
4759
connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
4860

49-
// receive JSON body
61+
// Receive JSON body
5062
InputStream stream = connection.getInputStream();
51-
String response = new Scanner(stream).useDelimiter("\\A").next();
63+
Scanner scanner = new Scanner(stream);
64+
String response = scanner.useDelimiter("\\A").next();
5265

53-
// construct result object for return
66+
// Construct result object for return
5467
SearchResults results = new SearchResults(new HashMap<String, String>(), response);
5568

56-
// extract Bing-related HTTP headers
69+
// Extract Bing-related HTTP headers
5770
Map<String, List<String>> headers = connection.getHeaderFields();
5871
for (String header : headers.keySet()) {
5972
if (header == null) continue; // may have null key
6073
if (header.startsWith("BingAPIs-") || header.startsWith("X-MSEdge-")) {
6174
results.relevantHeaders.put(header, headers.get(header).get(0));
6275
}
6376
}
64-
6577
stream.close();
78+
scanner.close();
79+
6680
return results;
6781
}
6882

69-
// pretty-printer for JSON; uses GSON parser to parse and re-serialize
83+
// Pretty-printer for JSON; uses GSON parser to parse and re-serialize
7084
public static String prettify(String json_text) {
71-
JsonParser parser = new JsonParser();
72-
JsonObject json = parser.parse(json_text).getAsJsonObject();
85+
JsonObject json = JsonParser.parseString(json_text).getAsJsonObject();
7386
Gson gson = new GsonBuilder().setPrettyPrinting().create();
7487
return gson.toJson(json);
7588
}
76-
77-
public static void main (String[] args) {
78-
if (subscriptionKey.length() != 32) {
79-
System.out.println("Invalid Bing Search API subscription key!");
80-
System.out.println("Please paste yours into the source code.");
81-
System.exit(1);
82-
}
83-
84-
try {
85-
System.out.println("Searching the Web for: " + searchTerm);
86-
87-
SearchResults result = SearchWeb(searchTerm);
88-
89-
System.out.println("\nRelevant HTTP Headers:\n");
90-
for (String header : result.relevantHeaders.keySet())
91-
System.out.println(header + ": " + result.relevantHeaders.get(header));
92-
93-
System.out.println("\nJSON Response:\n");
94-
System.out.println(prettify(result.jsonResponse));
95-
}
96-
catch (Exception e) {
97-
e.printStackTrace(System.out);
98-
System.exit(1);
99-
}
100-
}
10189
}
10290

10391
// Container class for search results encapsulates relevant headers and JSON data

0 commit comments

Comments
 (0)