Home About

February 24th, 2009

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

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: ,

15 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.

  9. Marco Says:

    Thanks, very useful code.

    Adding system.web reference in Visual C# express 2010 was a bit tricky.
    The way to go is to click on project/proprieties, application tab. Target Framework must be set to .NET Framework 4. Default is .NET Framework 4 Client Profile, which doesn’t have System.web.

  10. Ofer Says:

    Marco you rock!! i’ve searched how to do it, and you figured it out! Thanks!
    Martjin – Thanks for the class!!

  11. kyle Says:

    Thank you for this, it has helped me out with my problem.

    I am curious though, if I am posting to a web form which needs to redirect me, how can I achieve that instead of just receiving a string response?

  12. Mary Says:

    The code is working very well. I’ve tested the provided .php file on my server and it seems to do a very good job. I am impressed. It’s the first time when I test a .php file in this way. Thank you !

  13. Set up a Company Says:

    Finally some code that works! Thanks for this.

  14. John Says:

    Thank you for this great example and explanation! Everywhere else I have looked did not have a clear example/explanation. I also appreciate the post form on your server which helped greatly by providing a simple form which I could use in testing/debugging of my application.

  15. Juan Romero Says:

    Hi there, it’s a neat little class, but I believe you could do the same thing with the WebClient class. Check it out, it supports POSTing data. Cheers!


Most popular

    Sorry. No data so far.

Recent Comments
  • Juan Romero: Hi there, it’s a neat little class, but I believe you could do the same thing with the WebClient...
  • anthosh: Hey, THank you very much for your tutorial. It was awesome. But i have a problem that i am not able to...
  • bian: how to get passphase if i have encrypt and decrypt string?? Thanks alot
  • Michael: Hi, I really like your post, thanks a lot, it really helped clear up a few things I could not remember how...
  • Bharat Prajapati: i was trying to import keyword dictionary to this plugin which is in csv format, but i get an error...