Quickstart: Search for videos using the Bing Video Search REST API and Java
Use this quickstart to make your first call to the Bing Video Search API. This simple Java application sends an HTTP video search query to the API and displays the JSON response. Although this application is written in Java, the API is a RESTful Web service compatible with most programming languages.
The source code for this sample is available on GitHub with additional error handling, features, and code annotations.
Prerequisites
The Gson library.
Create and initialize a project
Create a new Java project in your favorite IDE or editor, and import the following libraries:
import java.net.*; import java.util.*; import java.io.*; import javax.net.ssl.HttpsURLConnection; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser;
Create a new class named
SearchResults
to store the headers and JSON response from the API.// Container class for search results encapsulates relevant headers and JSON data class SearchResults{ HashMap<String, String> relevantHeaders; String jsonResponse; SearchResults(HashMap<String, String> headers, String json) { relevantHeaders = headers; jsonResponse = json; } }
Create a new method named
SearchVideos()
with variables for your API endpoint host and path, your subscription key, and search term. This method returns aSearchResults
object.public static SearchResults SearchVideos (String searchQuery) throws Exception { static String subscriptionKey = "enter your key here"; static String host = "https://api.bing.microsoft.com"; static String path = "/bing/v7.0/videos/search"; static String searchTerm = "kittens"; }
Construct and send the search request
In the SearchVideos()
method, perform the following steps:
Construct the URL for your request by combining your API host, path, and encoded search query. Use
openConnection()
to create a connection, and then add your subscription key to theOcp-Apim-Subscription-Key
header.URL url = new URL(host + path + "?q=" + URLEncoder.encode(searchQuery, "UTF-8")); HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(); connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
Get the response from the API and store the JSON string.
InputStream stream = connection.getInputStream(); String response = new Scanner(stream).useDelimiter("\\A").next();
Use
getHeaderFields()
to extract the HTTP headers from the response, and store the Bing-related ones in theresults
object. Then, close the stream and return the result.// extract Bing-related HTTP headers Map<String, List<String>> 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;
Format the response
Create a method named prettify()
to format the response returned from the Bing Video API. Use the Gson library's JsonParser
to convert a JSON string to an object. Then, use GsonBuilder()
and toJson()
to create the formatted string.
// 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);
}
Send the request and print the response
In the main method of your application, call SearchVideos
with your search term. Then, print the HTTP headers stored in the response and the JSON string returned by the API.
public static void main (String[] args) {
SearchResults result = SearchVideos(searchTerm);
//print the Relevant HTTP Headers
for (String header : result.relevantHeaders.keySet())
System.out.println(header + ": " + result.relevantHeaders.get(header));
System.out.println(prettify(result.jsonResponse));
}
JSON response
A successful response is returned in JSON, as shown in the following example:
{
"_type": "Videos",
"instrumentation": {},
"readLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?q=kittens",
"webSearchUrl": "https://www.bing.com/videos/search?q=kittens",
"totalEstimatedMatches": 1000,
"value": [
{
"webSearchUrl": "https://www.bing.com/videos/search?q=kittens&view=...",
"name": "Top 10 cute kitten videos compilation",
"description": "HELP HOMELESS ANIMALS AND WIN A PRIZE BY CHOOSING...",
"thumbnailUrl": "https://tse4.mm.bing.net/th?id=OVP.n1aE_Oikl4MtzBb...",
"datePublished": "2014-11-12T22:47:36.0000000",
"publisher": [
{
"name": "Fabrikam"
}
],
"creator": {
"name": "Marcus Appel"
},
"isAccessibleForFree": true,
"contentUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
"hostPageUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
"encodingFormat": "h264",
"hostPageDisplayUrl": "https://www.fabrikam.com/watch?v=8HVWitAW-Qg",
"width": 480,
"height": 360,
"duration": "PT3M52S",
"motionThumbnailUrl": "https://tse4.mm.bing.net/th?id=OM.j4QyJAENJphdZQ_1501386166&pid=Api",
"embedHtml": "<iframe width=\"1280\" height=\"720\" src=\"https://www.fabrikam.com/embed/8HVWitAW-Qg?autoplay=1\" frameborder=\"0\" allowfullscreen></iframe>",
"allowHttpsEmbed": true,
"viewCount": 7513633,
"thumbnail": {
"width": 300,
"height": 168
},
"videoId": "655D98260D012432848F6558260D012432848F",
"allowMobileEmbed": true,
"isSuperfresh": false
},
. . .
],
"nextOffset": 36,
"queryExpansions": [
{
"text": "Kittens Meowing",
"displayText": "Meowing",
"webSearchUrl": "https://www.bing.com/videos/search?q=Kittens+Meowing...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
"thumbnail": {
"thumbnailUrl": "https://tse3.mm.bing.net/th?q=Kittens+Meowing&pid..."
}
},
{
"text": "Funny Kittens",
"displayText": "Funny",
"webSearchUrl": "https://www.bing.com/videos/search?q=Funny+Kittens...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
"thumbnail": {
"thumbnailUrl": "https://tse3.mm.bing.net/th?q=Funny+Kittens&..."
}
},
. . .
],
"pivotSuggestions": [
{
"pivot": "kittens",
"suggestions": [
{
"text": "Cat",
"displayText": "Cat",
"webSearchUrl": "https://www.bing.com/videos/search?q=Cat...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?...",
"thumbnail": {
"thumbnailUrl": "https://tse3.mm.bing.net/th?q=Cat&pid=Api..."
}
},
{
"text": "Feral Cat",
"displayText": "Feral Cat",
"webSearchUrl": "https://www.bing.com/videos/search?q=Feral+Cat...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search...",
"thumbnail": {
"thumbnailUrl": "https://tse3.mm.bing.net/th?q=Feral+Cat&pid=Api&..."
}
}
]
}
],
"relatedSearches": [
{
"text": "Kittens Being Born",
"displayText": "Kittens Being Born",
"webSearchUrl": "https://www.bing.com/videos/search?q=Kittens+Being+Born...",
"searchLink": "https://api.cognitive.microsoft.com/api/v7/videos/search?...",
"thumbnail": {
"thumbnailUrl": "https://tse1.mm.bing.net/th?q=Kittens+Being+Born&pid=..."
}
},
. . .
]
}