Today I needed to automate posting some data to a web form from a C# program, and sure enough this is not at all that difficult. But surprisingly you need to call quite a large number of methods to get your data ready to ship. A working code example only took a few minutes to write but it took quite a bit more time to clean things up. You can find the full implementation at the end of this post.
If you like to submit a POST form to your server the following will explain how to do create the program.
To help with debugging I created a tiny test script on my server to see if my code was working as advertised: http://www.dijksterhuis.org/test/post.php Please feel free to use this script to see if your program is working correctly.
My wrapper code is easy to use and allows for you to add any number of parameters to the POST request:
WebPostRequest myPost = new WebPostRequest("http://www.dijksterhuis.org/test/post.php"); myPost.Add("keyword","void"); myPost.Add("data","hello&+-[]");
I use the HttpUtility.UrlEncode method to ensure that all parameters containing weird symbols survive their trip over the Internet intact.
string Response = myPost.GetResponse();
The above function call executes the query and returns any response from the server. The test script simply echoes the parameters and their values.
using System; using System.Net; using System.Web; using System.Collections; using System.IO; namespace WebRequestExample { class WebPostRequest { WebRequest theRequest; HttpWebResponse theResponse; ArrayList theQueryData; public WebPostRequest(string url) { theRequest = WebRequest.Create(url); theRequest.Method = "POST"; theQueryData = new ArrayList(); } public void Add(string key, string value) { theQueryData.Add(String.Format("{0}={1}",key,HttpUtility.UrlEncode(value))); } public string GetResponse() { // Set the encoding type theRequest.ContentType="application/x-www-form-urlencoded"; // Build a string containing all the parameters string Parameters = String.Join("&",(String[]) theQueryData.ToArray(typeof(string))); theRequest.ContentLength = Parameters.Length; // We write the parameters into the request StreamWriter sw = new StreamWriter(theRequest.GetRequestStream()); sw.Write(Parameters); sw.Close(); // Execute the query theResponse = (HttpWebResponse)theRequest.GetResponse(); StreamReader sr = new StreamReader(theResponse.GetResponseStream()); return sr.ReadToEnd(); } } class MainClass { public static void Main(string[] args) { WebPostRequest myPost = new WebPostRequest("http://www.dijksterhuis.org/test/post.php"); myPost.Add("keyword","void"); myPost.Add("data","hello&+-[]"); Console.WriteLine(myPost.GetResponse()); } } }
This is a post from Martijn's C# Coding Blog.