Sending POST parameters via HTTP to a server in C#

December 21, 2009 by paulhenry · Comments Off
Filed under: C# Tutorials, Tutorials 

Here is a C# Method for sending data to a server via POST.

You would call this method like this:
get_post_response("http://somesite/", "email=email&password=password")

If any of the characters in the params contain special characters (Such as $, #, @) you must call HttpUtility.UrlEncode() on each param or on the entire param string. Here is how you do that: http://www.vcskicks.com/encode-url.php

public static string get_post_response(string page_url, string page_params) {
  var request = (HttpWebRequest)HttpWebRequest.Create(page_url);
  request.CookieContainer = new CookieContainer();
  request.CookieContainer.Add(session);
  request.ContentType = "application/x-www-form-urlencoded";
  request.Method = "POST";
  byte[] bytes = Encoding.ASCII.GetBytes(page_params);
  request.ContentLength = bytes.Length;
  using (Stream os = request.GetRequestStream()) {
     os.Write(bytes, 0, bytes.Length);
  }

  var resp = request.GetResponse();

  CookieContainer cookieJar = new CookieContainer();

  session = cookieJar.GetCookies(request.RequestUri);

  Stream respStream = resp.GetResponseStream();

  byte[] buffer = new byte[1024];
  string text = "";

  while (Convert.ToBoolean(respStream.Read(buffer, 0, buffer.Length)))
     text += Encoding.ASCII.GetString(buffer).Trim('\0');

  return text;
}

Enjoy!