Quickstart: Een query verzenden naar de Bing Local Business Search-API met behulp van Java
Waarschuwing
Op 30 oktober 2020 zijn de Zoeken in Bing API's verplaatst van Azure AI-services naar Zoeken in Bing Services. Deze documentatie is alleen bedoeld ter referentie. Zie de bing zoek-API-documentatie voor bijgewerkte documentatie. Zie Een Zoeken in Bing resource maken via de Azure Marketplace voor instructies voor het maken van nieuwe Azure-resources voor Bing Search.
Gebruik deze quickstart om te leren hoe u aanvragen verzendt naar de Bing Local Business Search-API, een Azure Cognitive Service. Hoewel deze eenvoudige toepassing in Java is geschreven, is de API een RESTful-webservice die compatibel is met elke programmeertaal die HTTP-aanvragen kan doen en JSON kan parseren.
In deze voorbeeldtoepassing worden lokale antwoordgegevens opgehaald uit de API voor een zoekquery.
Vereisten
- Een Azure-abonnement - Een gratis abonnement maken
- De Java Development Kit (JDK).
- Zodra u uw Azure-abonnement hebt, een Zoeken in Bing resource in de Azure Portal om uw sleutel en eindpunt op te halen. Nadat de app is geïmplementeerd, klikt u op Ga naar resource.
De aanvraag maken
Met de volgende code wordt een WebRequest
gemaakt, de koptekst van de toegangssleutel ingesteld en een query-tekenreeks toegevoegd voor hotel in Bellevue. Vervolgens wordt de aanvraag verzonden en het antwoord toegewezen aan een tekenreeks die de JSON-tekst moet bevatten.
// construct URL of search request (endpoint + query string)
URL url = new URL(host + path + "?q=" + URLEncoder.encode(searchQuery, "UTF-8") + &mkt=en-us");
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<String, String>(), response);
De volledige toepassing uitvoeren
De volgende code gebruikt de Bing Local Business Search-API om zoekresultaten te retourneren van de Bing-zoekmachine. Volg de volgende stappen om deze code uit te voeren:
- Download of installeer de gson-bibliotheek.
- Maak een nieuw Java-project in uw favoriete IDE of editor.
- Voeg de onderstaande code toe.
- Vervang de waarde
subscriptionKey
door een geldige toegangssleutel voor uw abonnement. - Voer het programma uit.
package localSearch;
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 (localSearch.java), you can compile and run this program at
* the command line as follows.
*
* javac localSearch.java -classpath .;gson-2.8.1.jar -encoding UTF-8
* java -cp .;gson-2.8.1.jar localSearch
*/
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class LocalSearchCls {
// ***********************************************
// *** Update or verify the following values. ***
// **********************************************
// Replace the subscriptionKey string value with your valid subscription key.
static String subscriptionKey = "YOUR-ACCESS-KEY";
static String host = "https://api.cognitive.microsoft.com/bing";
static String path = "/v7.0/localbusinesses/search";
static String searchTerm = "Hotel in Bellevue";
public static SearchResults SearchLocal (String searchQuery) throws Exception {
// construct URL of search request (endpoint + query string)
URL url = new URL(host + path + "?q=" + URLEncoder.encode(searchQuery, "UTF-8") + "&mkt=en-us");
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<String, String>(), response);
// 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;
}
// 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) {
try {
System.out.println("Searching the Web for: " + searchTerm);
SearchResults result = SearchLocal(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<String, String> relevantHeaders;
String jsonResponse;
SearchResults(HashMap<String, String> headers, String json) {
relevantHeaders = headers;
jsonResponse = json;
}
}