Website development and design blog, tutorials and inspiration

Posting Form Data to Remote Site using HttpWebRequest Post

By , 6th July 2011 in C#

Using this snippet of code you can easily send data using HttpWebRequest Post. The data is sent via the HTTP POST method to a remote server from your code behind.

This global code snippet for using HttpWebRequest Post can be used from a code behind web form, console application or Windows form application.

  1. string oid = "364826B3-7D29-4C2E-9568-C318C2B45F0C";
  2. string retURL = CurrentPage.Url;
  3. string remoteUrl = https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";
  4. string name = Request.Form["name"];
  5. string email = Request.Form["email"];
  6.  
  7. // Setup the POST data
  8. string poststring = String.Format("oid={0}&retURL={1}&name={2}&email={3}", oid, retURL, name, email);
  9. HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
  10.  
  11. httpRequest.Method = "POST";
  12. httpRequest.ContentType = "application/x-www-form-urlencoded";
  13.  
  14. // Convert the post string to a byte array
  15. byte[] bytedata = System.Text.Encoding.UTF8.GetBytes(poststring);
  16. httpRequest.ContentLength = bytedata.Length;
  17.  
  18. // Create the stream
  19. Stream requestStream = httpRequest.GetRequestStream();
  20. requestStream.Write(bytedata, 0, bytedata.Length);
  21. requestStream.Close();
  22.  
  23. // Get the response from remote server
  24. HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
  25. Stream responseStream = httpWebResponse.GetResponseStream();
  26.  
  27. System.Text.StringBuilder sb = new System.Text.StringBuilder();
  28. using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
  29. {
  30. string line;
  31. while ((line = reader.ReadLine()) != null)
  32. {
  33. sb.Append(line);
  34. }
  35. }
  36.  
  37. string serverResponse = sb.ToString();
Comments

There are no comments for this post. Be the first!

Leave a Reply

Your email address will not be published.