WebClient and HttpWebRequest class



Objective:

This article will discuss about, different way of consuming HTTP enabled service (like REST).This article, will explain about WebGet and HttpWebRequest. Before reading this article, I will suggest readers to read my previous articles on REST, ADO.NET Data Service and Cross Domain issue on our site.

Assumption:

  1. Already REST service has been created and hosted within placed client access policy file.
  2. There is a Silverlight Client. Which is going to consume WebGet service of REST

How to access HTTP based service in Silverlight?
  1. HTTP based service returned data on a HTTP request in a particular URI
     
  2. HTTP request can be send any type of URI like,

    http://trvlsdw002/synergyservices/appointmentservice.svc/Appointments/

    http://b068ltrv/SynergyService/AppointmentService.svc/Appointments/Mahesh

    http://localhost:22947/AppointmentService.svc"/Appointments/Praveen
     
  3. HTTP request is cofigured to work with , verb GET
     
  4. Required parameter to invoke service (WebGet sercvice) should be appended with URI

    1.gif
     
  5. The output service data is contained in HTTP Response.
     
  6. Format of data depends on service implementation, but it mainly in format of JOSN, XML or RSS.

Silverlight provides two methods for sending HTTP request
  1. WebClient
  2. HttpWebRequest

Difference between WebClient and HttpWebRequest
  1. HttpWebRequest supports large subset of HTTP Protocol , which makes it better option for advanced scenarios
  2. HttpWebRequest uses asynchronous programming model which uses delegates but on the other hand WebClient uses event based asynchronous programming model. So it is easier to use and it needs lessee line of code.
  3. Callback for WebClient is raised for HTTP Response and it is invoked on the same user interface thread. So it is easier to update property of UI element. That is why it is easy with WebClient to bind UI properties with data of Http response.

Whereas, HttpWebRequest callback run on different thread. So there is need of write extra code for UI binding.

WebClient

        Namespace: System.Net

        WebClient class is being used in Silverlight control which is hosted in a webpage.

The following table describes WebClient methods for uploading data to a resource.
Method Description
OpenWriteAsync Retrieves a Stream used to send data to the resource asynchronously, without blocking the calling thread.
UploadStringAsync Sends a String to the resource, without blocking the calling thread.

The following table describes WebClient methods for downloading data from a resource.
Method Description
DownloadStringAsync Downloads a String from a resource, without blocking the calling thread.
OpenReadAsync Returns the data from a resource asynchronously, without blocking the calling thread.


Steps to call Http based service
  1. Create URI , where request is to be sent

    string baseuri = "http://trvlsdw002/synergyservices/appointmentservice.svc/Appointments";

  2. Take care of cross domain issue here.
     
  3. Create instance of WebClient. don't forget to ass namespace System.Net

    WebClient wc = new WebClient();
     
  4. Now ,

    wc.DownloadStringCompleted += ParseProducts_AsXml;

    Here ParseProducts_AsXml is event , which will parse HTTP Response in XML format.

    If response format is JSON , then

    wc.DownloadStringCompleted += ParseProducts_AsJson

    Note : Here , ParseProducts_AsXml and ParseProducts_AsJson are user defined events. We need to define these events later.
     
  5. Now need to call ,

    Uri uri = new Uri(baseuri);
    wc.DownloadStringAsync(uri);

     
  6. Parse the response either as XML or as JOSN depending on response type of Http Response.

    For parsing as XML, given code might help. Here response is being passed in Product business object. In e.Result, result stream is coming to Silverlight application. Just need to desterilize that.

private void ParseProducts_AsXml(object sender, DownloadStringCompletedEventArgs e)
        {
            string abc = "";
            string rawXmlresponse = e.Result;
            XDocument xdoc = XDocument.Parse(rawXmlresponse);
            var query = from product in xdoc.Descendants(abc +  "Product")
                        select new Product
                                   {
                                       ProductId = product.Element("ProductId").Value.ToInt(),
                                       ProductName = product.Element("ProductName").Value,
                                       UnitPrice = product.Element("UnitPrice").Value.ToDecimal()
                                   };
            List<Product> products = query.ToList() as List<Product>;
            lstProducts.DataContext = products;

        }

For parsing as JOSN below code might help.

private void ParseProducts_AsJson(object sender, DownloadStringCompletedEventArgs e)
        {
            string raw = e.Result;
            JsonArray json;
            if (JsonArray.Parse(raw) as JsonArray == null)
                json = new JsonArray { JsonObject.Parse(raw) as JsonObject };
            else
                json = JsonArray.Parse(raw) as JsonArray;          

           var query = from product in json
                        select new Product
                                   {
                                      ProductId = (int)product["ProductId"],
                                      ProductName = (string)product["ProductName"],
                                      UnitPrice = (decimal)product["UnitPrice"]
                                   };
            List<Product> products = query.ToList() as List<Product>;
            lstProducts.DataContext = products;
        }


For Desterilizing as JOSN using DataContractJsonSerliazer

private void ParseProducts_AsJson_UsingDataContractJsonSerializer(object sender, DownloadStringCompletedEventArgs e)
        {
            string json = e.Result;
            DataContractJsonSerializer serializer =
                new DataContractJsonSerializer(typeof(List<Product>));
            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(products.GetType());

            MemoryStream
stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
            List<Product> products = serializer.ReadObject(stream) as List<Product>;
            stream.Close();
            lstProducts.DataContext = products;
        }


Note:

  1. There is no direct way, to expose DataContract to client in RESTful service. So workaround need to be done. There is need to create Business class at Silverlight client side. In above examples business class is Product.

  2. All the code written above is consuming REST service, which is returning List of appointments.

        [OperationContract(Name="GetAllAppointments")]
        [WebGet(UriTemplate = "/Appointments/")]
        List<AppointmentDTO> GetAppointments();


Here, AppointmentDTO is business object. Which has to be created at client side too?

Happy Coding!

Up Next
    Ebook Download
    View all
    Learn
    View all