Hızlı Başlangıç: Azure bilişsel hizmeti Bing Web Araması REST API'siyle web'de arama yapmak için Java kullanma
Uyarı
30 Ekim 2020'de Bing Arama API'leri Azure yapay zeka hizmetlerinden Bing Arama Hizmetlerine taşındı. Bu belgeler yalnızca başvuru için sağlanır. Güncelleştirilmiş belgeler için Bing arama API'sinin belgelerine bakın. Bing araması için yeni Azure kaynakları oluşturma yönergeleri için bkz. Azure Market aracılığıyla Bing Arama kaynağı oluşturma.
Bu hızlı başlangıçta, Bing Web Araması API'sine ilk çağrınızı yapmak için bir Java uygulaması kullanacaksınız. Bu Java uygulaması API'ye bir arama isteği gönderir ve JSON yanıtını gösterir. Bu uygulama Java dilinde yazılmış olsa da, API çoğu programlama diliyle uyumlu bir RESTful Web hizmetidir.
Önkoşullar
Bu hızlı başlangıcı çalıştırmak için aşağıdakilere ihtiyacınız olacaktır:
- JDK 7 veya 8
- Gson kitaplığı
- Abonelik anahtarı
Azure kaynağı oluşturma
Aşağıdaki Azure kaynaklarından birini oluşturarak Bing Web Araması API'sini kullanmaya başlayın:
- Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
- Hizmeti denemek için ücretsiz fiyatlandırma katmanını kullanın ve daha sonra üretim için ücretli bir katmana yükseltin.
- Kaynağı silene kadar Azure portal aracılığıyla kullanılabilir.
- Birden çok Azure AI hizmeti genelinde uygulamalarınız için aynı anahtarı ve uç noktayı kullanın.
Proje oluşturma ve bağımlılıkları içeri aktarma
Sık kullandığınız IDE ortamında veya düzenleyicide yeni bir Java projesi oluşturun ve aşağıdaki kitaplıkları içeri aktarın. Java nesnelerini JSON biçimine dönüştürmek için Gson kullanmanız gerekir.
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;
Maven POM dosyasında Gson tanımlama
Maven kullanıyorsanız, POM.xml'de Gson'u bildirin. Gson için yerel yükleme gerçekleştirdiyseniz bu adımı atlayın.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
BingWebSearch sınıfını tanımlama
BingWebSearch
sınıfını tanımlayın. Yöntemi de dahil olmak üzere bu hızlı başlangıçta incelediğimiz kodların main()
çoğunu içerir.
public class BingWebSearch {
// The code in the following sections goes here.
}
Değişkenleri tanımlama
Aşağıdaki kod , , host
path
ve searchTerm
kümelerini subscriptionKey
ayarlar. Bu kodu BingWebSearch
önceki bölümde açıklanan sınıfa ekleyin:
Değeri için
host
aşağıdaki kodda genel uç noktayı veya kaynağınızın Azure portal görüntülenen özel alt etki alanı uç noktasını kullanabilirsiniz.subscriptionKey
değerini Azure hesabınızdan geçerli bir abonelik anahtarı ile değiştirin.İsteğe bağlı olarak, değerini değiştirerek arama sorgusunu özelleştirin
searchTerm
.
// Enter a valid subscription key.
static String subscriptionKey = "enter key here";
/*
* If you encounter unexpected authorization errors, double-check these values
* against the endpoint for your Bing Web search instance in your Azure
* dashboard.
*/
static String host = "https://api.cognitive.microsoft.com";
static String path = "/bing/v7.0/search";
static String searchTerm = "Microsoft Cognitive Services";
İstek oluşturma
SearchWeb()
sınıfına BingWebSearch
dahil edilen yöntemi, öğesini oluşturururl
, yanıtı alır ve ayrıştırır ve Bing ile ilgili HTTP üst bilgilerini ayıklar.
public static SearchResults SearchWeb (String searchQuery) throws Exception {
// Construct the URL.
URL url = new URL(host + path + "?q=" + URLEncoder.encode(searchQuery, "UTF-8"));
// Open the connection.
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
// Receive the JSON response body.
InputStream stream = connection.getInputStream();
String response = new Scanner(stream).useDelimiter("\\A").next();
// Construct the result object.
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;
}
Yanıtı işleme
Yanıtı ayrıştırmak ve yeniden seri duruma getirmek için Gson kullanın.
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);
}
main metodunu tanımlama
main()
yöntemi gereklidir ve programı başlattığınızda çağrılan ilk yöntemdir. Bu uygulamada, öğesini doğrulayan subscriptionKey
bir istekte bulunan ve ardından JSON yanıtını yazdıran kodu içerir.
public static void main (String[] args) {
// Confirm the subscriptionKey is valid.
if (subscriptionKey.length() != 32) {
System.out.println("Invalid Bing Search API subscription key!");
System.out.println("Please paste yours into the source code.");
System.exit(1);
}
// Call the SearchWeb method and print the response.
try {
System.out.println("Searching the Web for: " + searchTerm);
SearchResults result = SearchWeb(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);
}
}
Arama sonuçları için kapsayıcı sınıfı oluşturma
SearchResults
Kapsayıcı sınıfı sınıfı dışında BingWebSearch
tanımlanır. Yanıtla ilgili üst bilgileri ve JSON verilerini içerir.
class SearchResults{
HashMap<String, String> relevantHeaders;
String jsonResponse;
SearchResults(HashMap<String, String> headers, String json) {
relevantHeaders = headers;
jsonResponse = json;
}
}
Hepsini bir araya getirin
Son adım kodunuzu derlemek ve çalıştırmaktır. Aşağıdaki komutları kullanın:
javac BingWebSearch.java -classpath ./gson-2.8.5.jar -encoding UTF-8
java -cp ./gson-2.8.5.jar BingWebSearch
Kodunuzu bizimkiyle karşılaştırmak isterseniz GitHub'daki örnek kodu inceleyebilirsiniz.
Örnek JSON yanıtı
Bing Web Araması API'si yanıtları JSON biçiminde döndürülür. Bu örnek yanıt, tek bir sonuç göstermek için kısaltıldı.
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "Microsoft Cognitive Services"
},
"webPages": {
"webSearchUrl": "https://www.bing.com/search?q=Microsoft+cognitive+services",
"totalEstimatedMatches": 22300000,
"value": [
{
"id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0",
"name": "Microsoft Cognitive Services",
"url": "https://www.microsoft.com/cognitive-services",
"displayUrl": "https://www.microsoft.com/cognitive-services",
"snippet": "Knock down barriers between you and your ideas. Enable natural and contextual interaction with tools that augment users' experiences via the power of machine-based AI. Plug them in and bring your ideas to life.",
"deepLinks": [
{
"name": "Face",
"url": "https://azure.microsoft.com/services/cognitive-services/face/",
"snippet": "Add facial recognition to your applications to detect, identify, and verify faces using a Face service from Microsoft Azure. ... Cognitive Services; Face service;"
},
{
"name": "Text Analytics",
"url": "https://azure.microsoft.com/services/cognitive-services/text-analytics/",
"snippet": "Cognitive Services; Text Analytics API; Text Analytics API . Detect sentiment, ... you agree that Microsoft may store it and use it to improve Microsoft services, ..."
},
{
"name": "Computer Vision API",
"url": "https://azure.microsoft.com/products/ai-services?activetab=pivot:visiontab",
"snippet": "Extract the data you need from images using optical character recognition and image analytics with Computer Vision APIs from Microsoft Azure."
},
{
"name": "Emotion",
"url": "https://www.microsoft.com/cognitive-services/en-us/emotion-api",
"snippet": "Cognitive Services Emotion API - microsoft.com"
},
{
"name": "Bing Speech API",
"url": "https://azure.microsoft.com/services/cognitive-services/speech/",
"snippet": "Add speech recognition to your applications, including text to speech, with a speech API from Microsoft Azure. ... Cognitive Services; Bing Speech API;"
},
{
"name": "Get Started for Free",
"url": "https://azure.microsoft.com/services/cognitive-services/",
"snippet": "Add vision, speech, language, and knowledge capabilities to your applications using intelligence APIs and SDKs from Cognitive Services."
}
]
}
]
},
"relatedSearches": {
"id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches",
"value": [
{
"text": "microsoft bot framework",
"displayText": "microsoft bot framework",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+bot+framework"
},
{
"text": "microsoft cognitive services youtube",
"displayText": "microsoft cognitive services youtube",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+youtube"
},
{
"text": "microsoft cognitive services search api",
"displayText": "microsoft cognitive services search api",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+search+api"
},
{
"text": "microsoft cognitive services news",
"displayText": "microsoft cognitive services news",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+news"
},
{
"text": "ms cognitive service",
"displayText": "ms cognitive service",
"webSearchUrl": "https://www.bing.com/search?q=ms+cognitive+service"
},
{
"text": "microsoft cognitive services text analytics",
"displayText": "microsoft cognitive services text analytics",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+text+analytics"
},
{
"text": "microsoft cognitive services toolkit",
"displayText": "microsoft cognitive services toolkit",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+toolkit"
},
{
"text": "microsoft cognitive services api",
"displayText": "microsoft cognitive services api",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+api"
}
]
},
"rankingResponse": {
"mainline": {
"items": [
{
"answerType": "WebPages",
"resultIndex": 0,
"value": {
"id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0"
}
}
]
},
"sidebar": {
"items": [
{
"answerType": "RelatedSearches",
"value": {
"id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches"
}
}
]
}
}
}