Silverlight 101: Make a GET request and a POST request.

Once a week I receive the same question about how to make a Http Web request in Silverlight, this is a pretty simple answer, yet I understand that if you starting in Silverlight you want to know how. For the benefit of not having to rely all the emails with the code, I’ll post it in my blog and just reference the url. So please find below the code to do just that. Of course this code is provided 'as-is', without any implied warranty.

 

Http GET request

WebClient wc = new WebClient(); 
string sRequest = "http://alpascual.com/blog/al/rss.aspx"; 
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); 
wc.DownloadStringAsync(new Uri(sRequest));

 

Http POST request

           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.Absolute)); 
            request.Method = "POST"; 
            // don't miss out this 
            request.ContentType = "application/x-www-form-urlencoded"; 
            request.BeginGetRequestStream(new AsyncCallback(RequestReady), request); 

        void RequestReady(IAsyncResult asyncResult) 
        { 
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; 
            Stream stream = request.EndGetRequestStream(asyncResult); 

            // Hack for solving multi-threading problem 
            // I think this is a bug 
            this.Dispatcher.BeginInvoke(delegate() 
            { 
                // Send the post variables 
                StreamWriter writer = new StreamWriter(stream);                
                writer.Write(sDataToPost); 
                writer.Flush(); 
                writer.Close(); 
                request.BeginGetResponse(new AsyncCallback(ResponseReady), request); 
            }); 
        }

 

        void ResponseReady(IAsyncResult asyncResult) 
        {           
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; 
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); 
            this.Dispatcher.BeginInvoke(delegate() 
            { 
                Stream responseStream = response.GetResponseStream(); 
                StreamReader reader = new StreamReader(responseStream); 
                // get the result text 
                string result = reader.ReadToEnd(); 

                // Send to the parser! 
                // TODO parse the result

            });       
        }

Cheers

Al

Follow me in twitter | bookmark me | Subscribe to my feed

Published Tuesday, March 03, 2009 1:26 PM by albertpascual

Comments

# Silverlight 101: Make a GET request and a POST request. - Albert Pascu

Tuesday, March 03, 2009 10:44 PM by Web Development Community

You are voted (great) - Trackback from Web Development Community

Leave a Comment

(required) 
(required) 
(optional)
(required)