Http Post in C#

Searched out on the internet and didn't really find anything that was horribly succinct, so I wrote this class for fun.  I had help from http://www.codeproject.com/cs/webservices/translation.asp.  I hope you enjoy!  Here's the code to call it:

PostSubmitter post=new PostSubmitter();
post.Url="http://seeker.dice.com/jobsearch/servlet/JobSearch";
post.PostItems.Add("op","100");
post.PostItems.Add("rel_code","1102");
post.PostItems.Add("FREE_TEXT","c# jobs");
post.PostItems.Add("SEARCH","");
post.Type=PostSubmitter.PostTypeEnum.Post;string result=post.Post();

And here's the class:

using System;using System.Text;using System.IO;using System.Web;using System.Net;using System.Collections.Specialized;

namespace Snowball.Common
{///


/// Submits post data to a url.///

public class PostSubmitter
{///
/// determines what type of post to perform.///

public enum PostTypeEnum
{///
/// Does a get against the source.///

Get,
///
/// Does a post against the source.///

Post
}

private string m_url=string.Empty;
private NameValueCollection m_values=new NameValueCollection();private PostTypeEnum m_type=PostTypeEnum.Get;///


/// Default constructor.///

public PostSubmitter()
{
}

///


/// Constructor that accepts a url as a parameter///

/// The url where the post will be submitted to.
public PostSubmitter(string url):this()
{
m_url=url;
}

///


/// Constructor allowing the setting of the url and items to post.///

/// the url for the post.
/// The values for the post.
public PostSubmitter(string url, NameValueCollection values):this(url)
{
m_values=values;
}

///


/// Gets or sets the url to submit the post to.///

public string Url
{get
{
return m_url;
}set
{
m_url=value;
}
}
///
/// Gets or sets the name value collection of items to post.///

public NameValueCollection PostItems
{get
{
return m_values;
}set
{
m_values=value;
}
}
///
/// Gets or sets the type of action to perform against the url.///

public PostTypeEnum Type
{get
{
return m_type;
}set
{
m_type=value;
}
}
///
/// Posts the supplied data to specified url.///

/// a string containing the result of the post.
public string Post()
{
StringBuilder parameters=new StringBuilder();for (int i=0;i < m_values.Count;i++)
{
EncodeAndAddItem(ref parameters,m_values.GetKey(i),m_values[i]);
}string result=PostData(m_url,parameters.ToString());return result;
}///
/// Posts the supplied data to specified url.///

/// The url to post to.
/// a string containing the result of the post.
public string Post(string url)
{
m_url=url;return this.Post();
}
///
/// Posts the supplied data to specified url.///

/// The url to post to.
/// The values to post.
/// a string containing the result of the post.
public string Post(string url, NameValueCollection values)
{
m_values=values;return this.Post(url);
}
///
/// Posts data to a specified url. Note that this assumes that you have already url encoded the post data.///

/// The data to post.
/// the url to post to.
/// Returns the result of the post.
private string PostData(string url, string postData)
{
HttpWebRequest request=null;
if (m_type==PostTypeEnum.Post)
{
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;using(Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
}
else
{
Uri uri = new Uri(url + "?" + postData);request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "GET";
}
string result=string.Empty;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{using (Stream responseStream = response.GetResponseStream())
{using (StreamReader readStream = new StreamReader (responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}return result;
}///
/// Encodes an item and ads it to the string.///

/// The previously encoded data.
/// The data to encode.
/// A string containing the old data and the previously encoded data.
private void EncodeAndAddItem(ref StringBuilder baseRequest, string key, string dataItem)
{if (baseRequest==null)
{
baseRequest=new StringBuilder();
}if (baseRequest.Length!=0)
{
baseRequest.Append("&");
}
baseRequest.Append(key);
baseRequest.Append("=");
baseRequest.Append(System.Web.HttpUtility.UrlEncode(dataItem));
}
}
}

This article is part of the GWB Archives. Original Author: Robert May

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.