Home About

February 24th, 2009

Simple class to submit (POST) a Web form from C# - 8

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());
		}	
	}
}
Be Sociable, Share!

Tags: ,

8 Responses to “Simple class to submit (POST) a Web form from C#”

  1. Reelix Says:

    The type or namespace name ‘HttpUtility’ does not exist in the namespace ‘System.Web’ (are you missing an assembly reference?)

  2. Martijn Says:

    Hi Reelix,

    You need to add System.Web to the project references.

    Thanks for pointing this out — I will update the post.

    Martijn

  3. Shakil Ahmed Says:

    Its really a nice article i ever seen.Its solve my problem

  4. Matteo Defanti Says:

    I’m a PHP newbie… Your solution is fantastic and very usefull… It’s the only i found that works :)
    congratulation again…

    A question… can you share the PHP code of http://www.dijksterhuis.org/test/post.php

    Thank you…

  5. Liz gwfservices Says:

    Hi!
    I’m Worse than a newbie, i’m positively petrified of php!!
    However i’ve just attempted my first feedback form, and it works! Miracle!
    Your help and advice on here is a great help!!
    LIZ

  6. Iflexion Says:

    Thanks a lot for the code. I’m working on a similar project right now and your information is just in time!

  7. Visual C# Kicks Says:

    Very useful class. I would just update the code to make use of List instead of ArrayList.

  8. Nelson Says:

    Saved me from doing it myself. Good article.


Most popular

    Sorry. No data so far.

Recent Comments
  • ARS: great plugin! I love it! but, it will be so nice if you can add attribute ‘title’ as one of...
  • Nelson: Saved me from doing it myself. Good article.
  • andy: i am currently playing taiwanese server wow in 奈辛瓦里(PVP) and i would like to realm transfer to somewhere there...
  • berties: any english speaking playing on a taiwanese server?
  • web application development: has C# search volume really so constant over the years? really surprising.