Quickstart: Send a search request to Bing Entity Search REST API using Java
Use this quickstart to make your first call to Bing Entity Search API and view the JSON response. This simple Java application sends a news search query to the API, and displays the response.
Although this application is written in Java, the API is a RESTful Web service compatible with most programming languages.
Prerequisites
- The Java Development Kit (JDK).
- 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.io.*; import java.net.*; import java.util.*; 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; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser;
In a new class, create variables for the API endpoint, your subscription key, and a search query.
public class EntitySearch { static String subscriptionKey = "ENTER KEY HERE"; static String host = "https://api.bing.microsoft.com"; static String path = "/v7.0/entities"; static String mkt = "en-US"; static String query = "italian restaurant near me"; //...
Construct a search request string
Create a function called
search()
that returns a JSONString
. url-encode your search query, and add it to a parameters string with&q=
. Add your market to the parameter string with?mkt=
.Create a URL object with your host, path, and parameters strings.
//... public static String search () throws Exception { String encoded_query = URLEncoder.encode (query, "UTF-8"); String params = "?mkt=" + mkt + "&q=" + encoded_query; URL url = new URL (host + path + params); //...
Send a search request and receive a response
In the
search()
function created above, create a newHttpsURLConnection
object withurl.openCOnnection()
. Set the request method toGET
, and add your subscription key to theOcp-Apim-Subscription-Key
header.//... HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey); connection.setDoOutput(true); //...
Create a new
StringBuilder
. Use a newInputStreamReader
as a parameter when instantiatingBufferedReader
to read the API response.//... StringBuilder response = new StringBuilder (); BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); //...
Create a
String
object to store the response from theBufferedReader
. Iterate through it, and append each line to the string. Then, close the reader and return the response.String line; while ((line = in.readLine()) != null) { response.append(line); } in.close(); return response.toString();
Format the JSON response
Create a new function called
prettify
to format the JSON response. Create a newJsonParser
, callparse()
on the JSON text, and then store it as a JSON object.Use the Gson library to create a new
GsonBuilder()
, usesetPrettyPrinting().create()
to format the JSON, and then return it.//... 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); } //...
Call the search function
From the main method of your project, call
search()
, and useprettify()
to format the text.public static void main(String[] args) { try { String response = search (); System.out.println (prettify (response)); } catch (Exception e) { System.out.println (e); } }
Example JSON response
A successful response is returned in JSON, as shown in the following example:
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "italian restaurant near me",
"askUserForLocation": true
},
"places": {
"value": [
{
"_type": "LocalBusiness",
"webSearchUrl": "https://www.bing.com/search?q=sinful+bakery&filters=local...",
"name": "Liberty's Delightful Sinful Bakery & Cafe",
"url": "https://www.contoso.com/",
"entityPresentationInfo": {
"entityScenario": "ListItem",
"entityTypeHints": [
"Place",
"LocalBusiness"
]
},
"address": {
"addressLocality": "Seattle",
"addressRegion": "WA",
"postalCode": "98112",
"addressCountry": "US",
"neighborhood": "Madison Park"
},
"telephone": "(800) 555-1212"
},
. . .
{
"_type": "Restaurant",
"webSearchUrl": "https://www.bing.com/search?q=Pickles+and+Preserves...",
"name": "Munson's Pickles and Preserves Farm",
"url": "https://www.princi.com/",
"entityPresentationInfo": {
"entityScenario": "ListItem",
"entityTypeHints": [
"Place",
"LocalBusiness",
"Restaurant"
]
},
"address": {
"addressLocality": "Seattle",
"addressRegion": "WA",
"postalCode": "98101",
"addressCountry": "US",
"neighborhood": "Capitol Hill"
},
"telephone": "(800) 555-1212"
},
. . .
]
}
}