Wednesday, July 13, 2011

HttpWebRequest and HttpWebResponse in Windows Phone 7 (wp7) Silverlight

I thought to add information regarding with HttpWebRequest / HttpWebResponse in Windows Phone 7. Though WebRequest and response in Windows Phone 7 is little bit different but it is easy. 
Here is code :

HttpWebRequest objRequest = null;
public static string myRequestData = string.Empty;
public String urlAddress = “Your URL”;

public void doSend()
objRequest = (HttpWebRequest)WebRequest.Create(urlAddress.ToString());
objRequest.ContentType ="application/x-www-form-urlencoded";
objRequest.Method = "POST";
//Adding headers
objRequest.Headers["Header"]= "Your Value";
objRequest.Headers["Content-Language"] = "en-US";

myRequestData = “Your Request data”;

//Begins the asynchronous request
objRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),objRequest);

private static void GetRequestStreamCallback(IAsyncResult asyncResult)
            HttpWebRequest objHttpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
            // End the operation
            Stream postStream = objHttpWebRequest.EndGetRequestStream(asyncResult);
            // Convert the string into a byte array.
            byte[] byteArray = Encoding.UTF8.GetBytes(myRequestData);
            // Write to the request stream.
            postStream.Write(byteArray, 0, myRequestData.Length);

            // Start the asynchronous operation to get the response
         request.BeginGetResponse(new AsyncCallback(GetResponseCallback), objHttpWebRequest );

private static void GetResponseCallback(IAsyncResult asyncResult)
            HttpWebRequest objHttpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse objHttpWebResponse = HttpWebResponse)request.EndGetResponse(asyncResult);
            Stream objStreamResponse = objHttpWebResponse .GetResponseStream();
            StreamReader objStreamReader = new StreamReader(objStreamResponse );
            string responseString =  objStreamReader.ReadToEnd();            // Got response here
             MessageBox.Show("RESPONSE :" + responseString);
            // Close the stream object
            objStreamResponse .Close();