Send data using POST / HttpWebRequest

As you may know, the POST method embeds the contents inside the stream itself, but the way this vars are actually structured can be very similar to the query string /GET method. 

   1: HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("");
   2: httpRequest.CookieContainer = Cookies;
   3: httpRequest.Method = "POST";
   4: httpRequest.ContentType = "application/x-www-form-urlencoded";

We are using a HttpWebRequest object to configure a web request, we are also setting the method to POST, last but absolutely not least, we are adding a header in the request to tell we are actually posting data url encoded.

This means, our data can be like this:

   1: string poststring = string.Format("COOKIEusername={0}&COOKIEpass={1}", "user", "password", captcha.Text);

In this example, we are assuming we want to loging to a website, and this webside actually use some kind of cookie based authentication mechanism, this is why we are using a CookieContainer.

   1: CookieContainer Cookies = new CookieContainer();

Later on, if you want to do some other request, and you need the site remembers you, you can actually pass in the same CookieContainer to the next requests.

But anyway, back to the subject:

   1: byte[] bytedata = Encoding.UTF8.GetBytes(poststring);
   2: httpRequest.ContentLength = bytedata.Length;

First, We are getting a byte[] array from our post var data, and encoding it using UTF8. (extended ASCII support for special chars)

Then, we just tell the response the length of our content, which is the same of our post data string. Then:

   1: Stream requestStream = httpRequest.GetRequestStream();
   2: requestStream.Write(bytedata, 0, bytedata.Length);
   3: requestStream.Close();

We are getting the request byte stream, then writing the POST data inside it.

Then, we just need to get the response (action that will perform the request we just configured before).

   1: HttpWebResponse httpWebResponse =
   2: (HttpWebResponse)httpRequest.GetResponse();

We’re done.

After this, we may want to get the response text to do some actions with it

   1: Stream responseStream = httpWebResponse.GetResponseStream();
   3: StringBuilder sb = new StringBuilder();
   5: using (StreamReader reader =
   6: new StreamReader(responseStream, System.Text.Encoding.UTF8))
   7: {
   8:     string line;
   9:     while ((line = reader.ReadLine()) != null)
  10:     {
  11:         sb.Append(line);
  12:     }
  13: }
  15: //use sb.ToString() to get the final html


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: