Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * BigDataCorp 2012
- * [2012_01_10] [ Marcello Lins ]
- *
- * This Class is responsible for executing Web Requests and hold possible error messages.
- * In order to make use of this Class, after instantiating it, the user have to set
- * up the URL used for the request by using the Public Property : "URL". This URL
- * will be used to create an HttpWebRequest Object.
- *
- * There are also public properties that can be used to setup the request parameters
- * such as timeout,referer,host and so on. Any other parameter that is not included here
- * can be added without any future mess.
- *
- * If the user needs the CookieContainer used on the requests to be reseted, he must implicitly
- * call the ClearCookies method, that will create a new CookieContainer overwriting the old one.
- *
- * After creating a request, and setting its parameters, the user can make use of methods such as
- * "Get" and "Post", both returning the response of their requests.
- *
- * There are Default Values for some Attributes of the request:
- * . Timeout = 8000 Miliseconds
- * . Encoding = "ISO-8859-1"
- * . Connections Limit = 500
- * . UserAgent = Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1
- *
- */
- using System;
- using System.Net;
- using System.IO;
- using BDC.BDCCommons;
- namespace WebUtilsLib
- {
- public class WebRequests
- {
- #region ** Private Attributes **
- // Private Attributes
- private CookieContainer m_CookieJar = null;
- private HttpWebRequest m_HttpWebRequest = null;
- private string m_userAgent = String.Empty;
- private string m_contentType = String.Empty;
- private string m_host = String.Empty;
- private string m_encoding = String.Empty;
- private string m_referer = String.Empty;
- private string m_error = String.Empty;
- private string m_origin = String.Empty;
- private string m_acceptEncoding = String.Empty;
- private int m_timeout = 0;
- private int m_connectionsLimit = 0;
- private bool m_allowAutoRedirect = false ;
- private WebHeaderCollection m_requestHeaders = null;
- // Error Logging Flag
- private bool m_logOnError = false;
- #endregion
- #region ** Public Properties **
- // Public Properties
- public HttpWebRequest InternalWebRequest
- {
- set { m_HttpWebRequest = value; }
- }
- /// <summary>
- /// UserAgent attribute
- /// Of the HttpWebRequest
- /// </summary>
- public string UserAgent
- {
- get { return m_userAgent; }
- set { m_userAgent = value; }
- }
- /// <summary>
- /// Host attribute
- /// Of the HttpWebRequest
- /// </summary>
- public string Host
- {
- get { return m_host; }
- set { m_host = value; }
- }
- /// <summary>
- /// ContentType attribute
- /// Of the HttpWebRequest
- /// </summary>
- public string ContentType
- {
- get { return m_contentType; }
- set { m_contentType = value; }
- }
- /// <summary>
- /// Encoding parameter
- /// Of the HttpWebRequest
- /// </summary>
- public string Encoding
- {
- get { return m_encoding; }
- set { m_encoding = value; }
- }
- /// <summary>
- /// Referer attribute
- /// Of the HttpWebRequest
- /// </summary>
- public string Referer
- {
- get { return m_referer; }
- set { m_referer = value; }
- }
- /// <summary>
- /// Timeout attribute
- /// Of the HttpWebRequest
- /// </summary>
- public int Timeout
- {
- get { return m_timeout; }
- set { m_timeout = value; }
- }
- /// <summary>
- /// ConnectionsLimit
- /// attribute
- /// Of the HttpWebRequest
- /// </summary>
- public int ConnectionsLimit
- {
- get { return m_connectionsLimit; }
- set { m_connectionsLimit = value; }
- }
- /// <summary>
- /// AllowAutoRedirect attribute
- /// Of the HttpWebRequest
- /// </summary>
- public bool AllowAutoRedirect
- {
- get { return m_allowAutoRedirect; }
- set { m_allowAutoRedirect = value; }
- }
- /// <summary>
- /// Origin attribute
- /// Of the HttpWebRequest
- /// </summary>
- public string Origin
- {
- get { return m_origin; }
- set { m_origin = value; }
- }
- /// <summary>
- /// AcceptEncoding
- /// attribute
- /// Of the HttpWebRequest
- /// </summary>
- public string AcceptEncoding
- {
- get { return m_acceptEncoding; }
- set { m_acceptEncoding = value; }
- }
- /// <summary>
- /// Headers attribute
- /// of the HttpWebRequest
- /// </summary>
- public WebHeaderCollection Headers
- {
- get { return m_requestHeaders; }
- set { m_requestHeaders = value; }
- }
- /// <summary>
- /// Message containing the
- /// last error that ocurred.
- /// Can be reseted by using ClearError
- /// Method
- /// </summary>
- public string Error
- {
- get { return m_error; }
- }
- /// <summary>
- /// Setter for LogOnError Attribute
- /// </summary>
- public bool LogErrorFlag
- {
- set { m_logOnError = value; }
- }
- #endregion
- /// <summary>
- /// Class Constructor
- /// </summary>
- /// <param name="LogOnError">Flag. If true then errors will be logged, else, logging is off</param>
- public WebRequests(bool LogOnError = false)
- {
- m_CookieJar = new CookieContainer();
- // Setting Default Values for some Attributes
- m_contentType = "application/x-www-form-urlencoded";
- m_userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1";
- m_encoding = "ISO-8859-1";
- m_timeout = 8000;
- m_connectionsLimit = 500;
- m_logOnError = LogOnError;
- m_requestHeaders = new WebHeaderCollection();
- }
- #region ** Clearing Methods **
- /// <summary>
- /// Clear the content of the
- /// Cookie Container class used in
- /// the requests
- /// </summary>
- public void ClearCookies()
- {
- m_CookieJar = new CookieContainer();
- }
- /// <summary>
- /// Clears the last error variable
- /// </summary>
- public void ClearError()
- {
- m_error = String.Empty;
- }
- #endregion
- #region ** HttpWebRequests Methods **
- /// <summary>
- /// Executes a Get
- /// creating an HttpWebRequest
- /// object based on previously
- /// set attributes
- /// </summary>
- /// <returns>Response of the Request. Empty string if any error ocurred.</returns>
- public string Get(string url)
- {
- string response = String.Empty;
- // Checking for empty url
- if (String.IsNullOrEmpty(url))
- {
- throw new Exception("URL para o Request não foi configurada ou é nula.");
- }
- try
- {
- // Re-Creating Request Object to avoid exceptions
- m_HttpWebRequest = WebRequest.Create (url) as HttpWebRequest;
- m_HttpWebRequest.CookieContainer = m_CookieJar;
- m_HttpWebRequest.Method = "GET";
- m_HttpWebRequest.UserAgent = m_userAgent;
- m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
- m_HttpWebRequest.Timeout = m_timeout;
- m_HttpWebRequest.ContentType = m_contentType;
- m_HttpWebRequest.Referer = m_referer;
- m_HttpWebRequest.AllowAutoRedirect = m_allowAutoRedirect;
- if (!String.IsNullOrEmpty(m_host))
- {
- m_HttpWebRequest.Host = m_host;
- }
- // Execute web request and wait for response
- using (HttpWebResponse resp = (HttpWebResponse) m_HttpWebRequest.GetResponse())
- {
- response= new StreamReader(resp.GetResponseStream()).ReadToEnd();
- }
- }
- catch (Exception ex)
- {
- m_error = ex.ToString();
- response = String.Empty;
- if (m_logOnError)
- LogWriter.Error(ex);
- }
- return response;
- }
- /// <summary>
- /// Executes a POST
- /// creating an HttpWebRequest
- /// object based on previously
- /// set attributes.
- /// </summary>
- /// <param name="postData">Parameters the Post Request</param>
- /// <returns>Response of the Request. Empty string if any error ocurred.</returns>
- public string Post (string url,string postData)
- {
- string response = String.Empty;
- // Checking for empty url
- if (String.IsNullOrEmpty(url))
- {
- throw new Exception("URL para o Request não foi configurada ou é nula.");
- }
- try
- {
- // Re-Creating Request Object to avoid exceptions
- m_HttpWebRequest = WebRequest.Create (url) as HttpWebRequest;
- m_HttpWebRequest.Method = "POST";
- m_HttpWebRequest.CookieContainer = m_CookieJar;
- m_HttpWebRequest.UserAgent = m_userAgent;
- m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
- m_HttpWebRequest.Timeout = m_timeout;
- m_HttpWebRequest.ContentType = m_contentType;
- m_HttpWebRequest.Referer = m_referer;
- m_HttpWebRequest.AllowAutoRedirect = m_allowAutoRedirect;
- if (!String.IsNullOrEmpty(m_host))
- m_HttpWebRequest.Host = m_host;
- // Counting the bytes to send
- byte[] bytes = System.Text.Encoding.GetEncoding(m_encoding).GetBytes(postData);
- int bytesSize = bytes.Length;
- m_HttpWebRequest.ContentLength = bytesSize;
- // Send Request
- using (var requestStream = m_HttpWebRequest.GetRequestStream())
- {
- requestStream.Write(bytes, 0, bytesSize);
- }
- // Get the Response
- using (WebResponse webResponse = m_HttpWebRequest.GetResponse())
- {
- if (webResponse != null)
- {
- // Read the Content of the response
- using (var responseStream = webResponse.GetResponseStream())
- {
- using (StreamReader Reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(m_encoding)))
- {
- response = Reader.ReadToEnd().Trim();
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- m_error = ex.ToString();
- response = String.Empty;
- if(m_logOnError)
- LogWriter.Error(ex);
- }
- return response;
- }
- #endregion
- }
- }
Add Comment
Please, Sign In to add comment