Posting Form Data to Remote Site using C# and HttpWebRequest

Posting form data using C# and HttpWebRequest is easy. The data is sent via the HTTP POST method to a remote server from your code behind.

By Tim TrottC# ASP.Net MVC • July 6, 2011
Posting Form Data to Remote Site using C# and HttpWebRequest

In the world of .NET development, understanding how to use HttpWebRequest is essential for interacting with web servers programmatically. Whether you're building a web scraper, consuming APIs, or handling HTTP requests in your application, HttpWebRequest provides a versatile and powerful toolset.

The HttpWebRequest class supports the WebRequest properties and methods, as well as extra properties and methods that allow the user to connect directly with servers over HTTP(S).

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

Do not use the HttpWebRequest constructor. Make use of the WebRequest.Create a method instead for creating new HttpWebRequest objects. WebRequest.Create returns a HttpWebRequest object if the scheme for the Uniform Resource Identifier (URI) is http:// or https://.

The below example is for posting form data via Web-to-Lead to Salesforce API endpoint.

C#
string oid = "364826B3-7D29-4C2E-9568-C318C2B45F0C";
string retURL = CurrentPage.Url;
string remoteUrl = https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8";
string name = Request.Form["name"];
string email = Request.Form["email"];

// Setup the POST data
string poststring = String.Format("oid={0}&retURL={1}&name={2}&email={3}", oid, retURL, name, email);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);

httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";

// Convert the post string to a byte array
byte[] bytedata = System.Text.Encoding.UTF8.GetBytes(poststring);
httpRequest.ContentLength = bytedata.Length;

// Create the stream
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();

// Get the response from remote server
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();

System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        sb.Append(line);
    }
}

string serverResponse = sb.ToString();

Cookies are disabled by default for security reasons. Use the CookieContainer property to enable cookies if you want to use them.

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has only 1 comment. Why not join the discussion!

New comments for this post are currently closed.