HTTP Post from code behind in C#
Sometimes you may be required to send some data to a remote site from the code behind via HTTP. Generally this can easily be perfomed if the site allows for GET submissions. However sometimes the site will only accept POST submissions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | /// <summary> /// Added to handle form submission to remote server /// </summary> private void PostToRemoteCrm() { // build post variables ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "hiddenvar1=" + HttpUtility.UrlEncode("hiddenvalue"); postData += "&First+Name=" + HttpUtility.UrlEncode(tbFirstName.Text); postData += "&Last+Name=" + HttpUtility.UrlEncode(tbLastName.Text); postData += "&Email=" + HttpUtility.UrlEncode(tbEmail.Text); postData += "&Phone=" + HttpUtility.UrlEncode(tbHomePhone.Text); postData += "&Mobile=" + HttpUtility.UrlEncode(tbMobilePhone.Text); postData += "&Street=" + HttpUtility.UrlEncode(tbAddress1.Text + "\r\n" + tbAddress2.Text); byte[] data = encoding.GetBytes(postData); // Prepare web request... HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://the.remote.server.com/form/submission.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(); } |
Thanks to http://www.netomatix.com/httppostdata.aspx for the example.
Tags: C# Programming, code behind, form submission, http post