Skip to content

Commit 4dbe134

Browse files
committed
updating java and nodejs quickstarts
1 parent e747460 commit 4dbe134

File tree

2 files changed

+202
-0
lines changed

2 files changed

+202
-0
lines changed
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
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+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
//Copyright (c) Microsoft Corporation. All rights reserved.
2+
//Licensed under the MIT License.
3+
4+
'use strict';
5+
6+
let https = require('https');
7+
8+
// **********************************************
9+
// *** Update or verify the following values. ***
10+
// **********************************************
11+
12+
// Replace the subscriptionKey string value with your valid subscription key.
13+
let subscriptionKey = 'Copy Your Key Here';
14+
15+
// Verify the endpoint URI. At this writing, only one endpoint is used for Bing
16+
// search APIs. In the future, regional endpoints may be available. If you
17+
// encounter unexpected authorization errors, double-check this host against
18+
// the endpoint for your Bing Search instance in your Azure dashboard.
19+
let host = 'api.cognitive.microsoft.com';
20+
let path = '/bing/v7.0/images/search';
21+
22+
let term = 'tropical ocean';
23+
24+
let response_handler = function (response) {
25+
let body = '';
26+
response.on('data', function (d) {
27+
body += d;
28+
});
29+
response.on('end', function () {
30+
let imageResults = JSON.parse(body);
31+
if (imageResults.value.length > 0) {
32+
let firstImageResult = imageResults.value[0];
33+
console.log(`Image result count: ${imageResults.value.length}`);
34+
console.log(`First image insightsToken: ${firstImageResult.imageInsightsToken}`);
35+
console.log(`First image thumbnail url: ${firstImageResult.thumbnailUrl}`);
36+
console.log(`First image web search url: ${firstImageResult.webSearchUrl}`);
37+
}
38+
else {
39+
console.log("Couldn't find image results!");
40+
}
41+
42+
43+
44+
});
45+
response.on('error', function (e) {
46+
console.log('Error: ' + e.message);
47+
});
48+
};
49+
50+
let bing_image_search = function (search) {
51+
console.log('Searching images for: ' + term);
52+
let request_params = {
53+
method : 'GET',
54+
hostname : host,
55+
path : path + '?q=' + encodeURIComponent(search),
56+
headers : {
57+
'Ocp-Apim-Subscription-Key' : subscriptionKey,
58+
}
59+
};
60+
61+
let req = https.request(request_params, response_handler);
62+
req.end();
63+
}
64+
65+
if (subscriptionKey.length === 32) {
66+
bing_image_search(term);
67+
} else {
68+
console.log('Invalid Bing Search API subscription key!');
69+
console.log('Please paste yours into the source code.');
70+
}

0 commit comments

Comments
 (0)