Monday, September 15, 2008

Http Post Post Submiter

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.
///
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.
///
string Post()
{
StringBuilder parameters = new StringBuilder();
for (int i = 0; i < result =" PostData(m_url,">
string Post(string url)
{
m_url = url;
return this.Post();
}
string Post(string url, NameValueCollection values)
{
m_values = values;
return this.Post(url);
}
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;
}
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));
}
}

No comments: