How to have your application POST to a web page.

First thing that I hear is why would I POST rather than GET.

Post send the information back on the HTTP POST stream. Get sends the information back on the URL. I can actually mimic a webbrowser’s submit with POST. There are plenty of benefits to that, which I will not get into

Setup:

Add to your project either System.Web, if you are going to use the HTTPWebRequest and HTTPWebResponse objects. Otherwise add System.Net for the non-HTTP versions of those classes.

Step 1: Declair the post address and request object.

string url = “http://some.web.site.com“;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

Step 2: Build your posting data, and encode it.

string data = String.Format(“someparameter={0}&someotherparameter={1}“,
myParameter, myOtherParameter);
//myParameter and myOtherParameter are declared somewhere else.
byte[] buffer = Encoding.UTF8.GetBytes(data);

Step 3: Using the request declaired earlier, set parameters.

string proxy = null; //This line and the proxy property are not needed for local posting.
req.Method = “POST“;
req.ContentType = “application/x-www-form-urlencoded“;
//You can try other encodings, but this one I know works.
req.ContentLength = buffer.Length;
req.Proxy = new
WebProxy(proxy, true);
// See the proxy not from above.
req.CookieContainer = new CookieContainer(); // I have found that this is needed more times than not for round trip calls.

Step 4: Send the data.

Stream reqs = req.GetRequestStream(); //add form data to request stream
reqs.Write(buffer, 0, buffer.Length);
reqs.Flush();
reqs.Close(); //at this point, you have sent and closed the transmission.

Step 5: Respond to the server.

HttpWebResponse res = (HttpWebResponse)req.GetResponse(); //Create a response handler.
Stream resst = res.GetResponseStream();
//Get the response
StreamReader sr = new StreamReader(resst);
string response = sr.ReadToEnd(); //Dump to string
sr.Close();

Step 6: Now you can dispose of everything.

Do not do this step prematurely.
A lot of these objects are IDisposable.
So call it when you see it.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.