Using the API Version 2.0 Beta with Java and the API's XML interface

Using the API Version 2.0 Beta with Java and the API's XML interface

Rate This
  • Comments (11)

Author: Roopali Kaujalgi, Program Manager II, Bing API

This is the first of a series of posts that show how you can use the API with Java. This post shows how you can use Java to create a console application that sends a request to the API's XML interface and displays the results. The last post in the series will include a pointer to a site from which you can download all instructions and code associated with each post in the series.

Coming next: Using the API with Java and the SOAP interface

 

Requirements

Demonstrates

These code samples demonstrates how to:

  • Send a request to the Live Search XML interface and the Web SourceType
  • Display the Live Search response as results

To run the sample

  1. Create files named WebSample.java and APINameSpaceContext.java.
  2. Copy "File 1 Content: WebSample.java" from the section of that name in this post to WebSample.java.
  3. Copy "File 2 Content: APINameSpaceContext.java" from the section of that name in this post to APINameSpaceContext.java.
  4. In WebSample.java, substitute your AppId for Insert your AppId here.
  5. Edit your computer's PATH environment variable to include the bin directory of the JAVA installation.
  6. Compile the 2 files.
  7. Run the sample (for example, typing java WebSample from the command line in the directory containing WebSample.java).

File Content

 

The remainder of this post consists of the content (in the form of code) that you will copy in Steps 2 and 3 of "To Run the Sample."

File 1 Content: WebSample.java

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

//Live Search API 2.0 code sample demonstrating the use of the
//Web SourceType over the XML Protocol.
class WebSample 
{
	static XPathFactory factory = null;
	static XPath xpath = null;
	static XPathExpression expr = null;

	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, 
XPathExpressionException { // Build the request. String requestURL = BuildRequest(); // Send the request to the Live Search Service and get the response. Document doc = GetResponse(requestURL); if(doc != null) { // Display the response obtained from the Live Search Service. DisplayResponse(doc); } } private static String BuildRequest() { // Replace the following string with the AppId you received from the // Live Search Developer Center. String AppId = "Insert your AppId here."; String requestString = "http://api.search.live.net/xml.aspx?" // Common request fields (required) + "AppId=" + AppId + "&Query=msdn blogs" + "&Sources=Web" // Common request fields (optional) + "&Version=2.0" + "&Market=en-us" + "&Adult=Moderate" // Web-specific request fields (optional) + "&Web.Count=10" + "&Web.Offset=0" + "&Web.FileType=DOC" + "&Web.Options=DisableHostCollapsing+DisableQueryAlterations"; return requestString; } private static Document GetResponse(String requestURL) throws ParserConfigurationException, SAXException,
IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = null; DocumentBuilder db = dbf.newDocumentBuilder(); if (db != null) { doc = db.parse(requestURL); } return doc; } private static void DisplayResponse(Document doc) throws XPathExpressionException { factory = XPathFactory.newInstance(); xpath = factory.newXPath(); xpath.setNamespaceContext(new APINameSpaceContext()); NodeList errors = (NodeList) xpath.evaluate("//api:Error",doc,XPathConstants.NODESET); if(errors != null && errors.getLength() > 0 ) { // There are errors in the response. Display error details. DisplayErrors(errors); } else { DisplayResults(doc); } } private static void DisplayResults(Document doc) throws XPathExpressionException { String version = (String)xpath.evaluate("//@Version",doc,XPathConstants.STRING); String searchTerms = (String)xpath.evaluate("//api:SearchTerms",doc,XPathConstants.STRING); int total = Integer.parseInt((String)xpath.evaluate("//web:Web/web:Total",doc,XPathConstants.STRING)); int offset = Integer.parseInt((String)xpath.evaluate("//web:Web/web:Offset",doc,
XPathConstants.STRING)); NodeList results = (NodeList)xpath.evaluate"//web:Web/web:Results/web:WebResult",doc,
XPathConstants.NODESET); // Display the results header. System.out.println("Live Search API Version " + version); System.out.println("Web results for " + searchTerms); System.out.println("Displaying " + (offset+1) + " to " + (offset +
results.getLength()) + " of " + total + " results "); System.out.println(); // Display the Web results. StringBuilder builder = new StringBuilder(); for(int i = 0 ; i < results.getLength(); i++) { NodeList childNodes = results.item(i).getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { if(!childNodes.item(j).getLocalName().equalsIgnoreCase("DisplayUrl")) { String fieldName = childNodes.item(j).getLocalName(); if(fieldName.equalsIgnoreCase("DateTime")) { fieldName = "Last Crawled"; } builder.append(fieldName + ":" + childNodes.item(j).getTextContent()); builder.append("\n"); } } builder.append("\n"); } System.out.println(builder.toString()); } private static void DisplayErrors(NodeList errors) { System.out.println("Live Search API Errors:"); System.out.println(); for (int i = 0; i < errors.getLength(); i++) { NodeList childNodes = errors.item(i).getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { System.out.println(childNodes.item(j).getLocalName() + ":" + childNodes.item(j).getTextContent()); } System.out.println(); } } }

File 2 Content: APINameSpaceContext.java

import java.util.Iterator;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;

// Map prefixes to Namespace URIs
public class APINameSpaceContext implements NamespaceContext 
{
	static final String WEB_NAMESPACE =  "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web";
	static final String API_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element";
	static final String SPELL_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/spell";
	static final String RS_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/relatedsearch";
	static final String PB_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/phonebook";
	static final String MM_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia";
	static final String AD_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/ads";
	static final String IA_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/instantanswer";
	static final String NEWS_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/news";
	static final String ENCARTA_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/encarta";

	public String getNamespaceURI(String prefix) 
	{
		if (prefix == null) throw new NullPointerException("Null prefix");
		else if ("api".equals(prefix)) return API_NAMESPACE;
		else if ("web".equals(prefix)) return WEB_NAMESPACE;
		return XMLConstants.NULL_NS_URI;
	}
	
	// This method isn't necessary for XPath processing.
	public String getPrefix(String uri) 
	{
		throw new UnsupportedOperationException();
	}
	
	public Iterator getPrefixes(String arg0) 
	{
		throw new UnsupportedOperationException();
	}
}

Join Bing Community
  • the word is so small

  • very good thanks

  • I have made a lot of improvement using the API with Java.

  • Hi,

    I'm trying to have look at the actual .xsds but when I try to get them, e.g. schemas.microsoft.com/.../web, I always get a 404 file not found. How can I get to the actual files?

    pls. help...

  • I love Bing Search so Much!

  • By itself it works great... There seems to be an issue when using this together with some oracle systems.

    Exception in thread "main" javax.xml.parsers.FactoryConfigurationError: Provider oracle.xml.jaxp.JXDocumentBuilderFactory not found

    at javax.xml.parsers.DocumentBuilderFactory.newInstance(DocumentBuilderFactory.java:129)

  • Thanks, works fine!

  • hi,

    I begin to use the api, and I am searching how to determine the "hit" of documents related to a submited query.

    many thanks,

  • hi thanks your sharing i want to use

    api.search.live.net/search.wsdl in my application i dont know how to do it i use eclipse . I dont know where i am start is there anyone can help me

  • Thanks Roopali, this was really useful. I was trying to use an adaptation of this to work with the sourcetype of translation - most of it works - but have trouble traversing the response - the results returned and tra prefix that comes back - haven't been able to figure how to traverse it.

  • Please help me....

    I m facing these errors....

    E:\java db>java WebSample

    Exception in thread "main" java.io.IOException: Server returned HTTP response co

    de: 400 for URL: api.search.live.net/xml.aspx api key"&Query=msdn blogs&Sources=Web&Version=2.0&Market=en-us&Adult=

    Moderate&Web.Count=10&Web.Offset=0&Web.FileType=DOC&Web.Options=DisableHostColla

    psing+DisableQueryAlterations

           at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon

    nection.java:1225)

           at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrent

    Entity(XMLEntityManager.java:677)

           at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineD

    ocVersion(XMLVersionDetector.java:186)

           at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(X

    ML11Configuration.java:771)

           at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(X

    ML11Configuration.java:737)

           at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.

    java:107)

           at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.

    java:225)

           at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Doc

    umentBuilderImpl.java:283)

           at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:180)

           at WebSample.GetResponse(WebSample.java:76)

           at WebSample.main(WebSample.java:30)

Page 1 of 1 (11 items)