Skip to content

Instantly share code, notes, and snippets.

@munr
Last active August 29, 2015 14:15
Show Gist options
  • Save munr/b076aa4ff48c90e5979c to your computer and use it in GitHub Desktop.
Save munr/b076aa4ff48c90e5979c to your computer and use it in GitHub Desktop.
Class for easily posting JSON or XML Data in C#
public class FormPoster
{
#region Private Variables
private readonly Dictionary<string, Header> m_HeaderList = new Dictionary<string, Header>();
private readonly Dictionary<string, Parameter> m_ParameterList = new Dictionary<string, Parameter>();
private CookieContainer m_CookieContainer = new CookieContainer();
private string m_RawPostData;
#endregion
#region Accessors
public string Username { get; set; }
public string Password { get; set; }
public string Url { get; set; }
public string ContentType { get; set; }
public string AcceptType { get; set; }
public string Method { get; set; }
#endregion
#region Constructor
public FormPoster(string url, string method = null)
{
Url = url;
Method = method ?? "POST";
ContentType = "application/x-www-form-urlencoded";
}
#endregion
#region Public Helper Methods
public void AddHeader(string name, object value)
{
var header = new Header
{
Name = name,
Value = (value == null) ? null : value.ToString()
};
m_HeaderList[name] = header;
}
public void AddParameter(string name, object value)
{
var parameter = new Parameter
{
Name = name,
Value = (value == null) ? null : value.ToString()
};
m_ParameterList[name] = parameter;
}
public void SetCookieContainer(CookieContainer cookieContainer)
{
m_CookieContainer = cookieContainer;
}
public void SetJsonData(object o)
{
var serializer = new JavaScriptSerializer();
SetJsonString(serializer.Serialize(o));
}
public void SetJsonString(string s)
{
m_RawPostData = s;
ContentType = "application/json";
}
#endregion
#region Helper Methods
private string GetPostData()
{
if (!string.IsNullOrEmpty(m_RawPostData))
return m_RawPostData;
return GetParametersForPosting();
}
private string GetParametersForPosting()
{
var postData = new StringBuilder();
foreach (var parameter in m_ParameterList.Values)
{
var encodedValue = HttpUtility.UrlEncode(parameter.Value);
postData.Append(parameter.Name);
postData.AppendFormat("={0}&", encodedValue);
}
var returnVal = postData.ToString();
if (returnVal.EndsWith("&"))
returnVal = returnVal.Substring(0, returnVal.Length - 1);
return returnVal;
}
#endregion
#region Helper Classes
private struct Header
{
/// <summary>
/// Header Name
/// </summary>
public string Name;
/// <summary>
/// Header Value
/// </summary>
public string Value;
}
private struct Parameter
{
/// <summary>
/// Parameter Name
/// </summary>
public string Name;
/// <summary>
/// Parameter Value
/// </summary>
public string Value;
}
#endregion
public void SetBasicAuthHeader(string username, string password)
{
var encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
AddHeader("Authorization", "Basic " + encoded);
}
/// <summary>
/// Performs the post and returns the response
/// </summary>
public PostResponse Post()
{
// Get the parameters string ready for posting
var postData = GetPostData();
// Construct the web request
var webRequest = (HttpWebRequest)WebRequest.Create(Url);
webRequest.Method = Method;
webRequest.ContentType = ContentType;
webRequest.ContentLength = postData.Length;
if (!string.IsNullOrEmpty(AcceptType))
webRequest.Accept = AcceptType;
// Set credentials if required
if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
webRequest.Credentials = new NetworkCredential(Username, Password);
// Set the cookie container if required
if (m_CookieContainer != null)
webRequest.CookieContainer = m_CookieContainer;
// Add the headers
foreach (var header in m_HeaderList.Values)
webRequest.Headers.Add(header.Name, header.Value);
// Post the data
if (postData.Length > 0)
{
using (var streamOut = new StreamWriter(webRequest.GetRequestStream(), Encoding.ASCII))
{
streamOut.Write(postData);
streamOut.Close();
}
}
var postResponse = new PostResponse();
// Get the response
using (var response = webRequest.GetResponse())
{
foreach (var header in response.Headers)
{
postResponse.Headers[header.ToString()] = response.Headers[header.ToString()];
}
using (var rs = response.GetResponseStream())
{
if (rs != null)
{
using (var streamIn = new StreamReader(rs))
{
postResponse.Text = streamIn.ReadToEnd();
streamIn.Close();
}
}
}
}
postResponse.CookieContainer = webRequest.CookieContainer;
return postResponse;
}
public class PostResponse
{
public PostResponse()
{
Headers = new Dictionary<string, string>();
}
public string Text { get; set; }
public Dictionary<string, string> Headers { get; set; }
public CookieContainer CookieContainer { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment