Create HttpRequest from code behind

by Miro 12. November 2008 12:42

 //StringBuilder is not necessary - a string would do

                                StringBuilder sb = new StringBuilder();
                                ASCIIEncoding encoding = new ASCIIEncoding();

 //Add the parameters

                                sb.Append("par1=abc");
                                sb.Append("&par2=123");

                                byte[] data = encoding.GetBytes(sb.ToString());

                                // Prepare web request...
                                HttpWebRequest myRequest = "http:\\AnotherWebSite\ProcessingPage.aspx";
                                myRequest.Method = "POST";
                                myRequest.ContentType = "application/x-www-form-urlencoded";
                                myRequest.ContentLength = data.Length;
                                Stream newStream = myRequest.GetRequestStream();
// Send the data.
                                newStream.Write(data, 0, data.Length);
                                newStream.Close();

//get the response
                                HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
                                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                                string r = reader.ReadToEnd();
                                reader.Close();

//do something with the response
                                Page.Response.Write(r);

Tags:

.NET

Powered by BlogEngine.NET
Contents copyright 2008 Mirocle Pty. Ltd. All Rights Reserved.