Wednesday, March 24, 2010

Bing API 2.0: Consume results as XML with .NET

In the post 'Get Started' I told you that you can use HTTP GET to send requests. This means that we can send the HTTP request and get the response using .NET as well.

An example

In this example I use an HttpWebRequest to create a request and an HttpWebResponse to get the response. You can find these classes in the System.Net namespace.

   1:  namespace BingAPIConsumeXML
   2:  {
   3:      class Program
   4:      {
   5:          static void Main(string[] args)
   6:          {
   7:              string url = "[YourAppId]&query=Mini+Cooper+S&sources=image";
   9:              //Request and get the Response
  10:              HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
  11:              HttpWebResponse resp = (HttpWebResponse)req.GetResponse();          
  13:              //Write the Byte Array to the console as a string
  14:              StreamReader reader = new StreamReader(resp.GetResponseStream());
  15:              string res = reader.ReadToEnd();
  17:              Console.WriteLine(res);
  19:              Console.ReadLine();
  20:          }
  21:      }
  22:  }

You can parse the XML response using your favorite .NET parsing method.

In this example I simple load the ResponseStream into a StreamReader and write the Stream to a string.

This post is part of the Bing API 2.0 series.

1 comment:

  1. Thank You

    The given information is very effective
    i will keep updated with the same

    industrial automation