MarcelloLins

WebRequests Class

Feb 7th, 2012
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.62 KB | None | 0 0
  1. /*
  2.  *  BigDataCorp 2012
  3.  *  [2012_01_10] [ Marcello Lins ]
  4.  *
  5.  *   This Class is responsible for executing Web Requests and hold possible error messages.
  6.  *   In order to make use of this Class, after instantiating it, the user have to set
  7.  *   up the URL used for the request by using the Public Property : "URL". This URL
  8.  *   will be used to create an HttpWebRequest Object.
  9.  *  
  10.  *   There are also public properties that can be used to setup the request parameters
  11.  *   such as timeout,referer,host and so on. Any other parameter that is not included here
  12.  *   can be added without any future mess.
  13.  *  
  14.  *   If the user needs the CookieContainer used on the requests to be reseted, he must implicitly
  15.  *   call the ClearCookies method, that will create a new CookieContainer overwriting the old one.
  16.  *  
  17.  *   After creating a request, and setting its parameters, the user can make use of methods such as
  18.  *   "Get" and "Post", both returning the response of their requests.
  19.  *  
  20.  *   There are Default Values for some Attributes of the request:
  21.  *     . Timeout           = 8000 Miliseconds
  22.  *     . Encoding          = "ISO-8859-1"
  23.  *     . Connections Limit = 500
  24.  *     . UserAgent         = Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1
  25.  *    
  26.  */
  27.  
  28. using System;
  29. using System.Net;
  30. using System.IO;
  31. using BDC.BDCCommons;
  32.  
  33. namespace WebUtilsLib
  34. {
  35.     public class WebRequests
  36.     {
  37.         #region ** Private Attributes **
  38.  
  39.         // Private Attributes
  40.         private CookieContainer     m_CookieJar         = null;
  41.         private HttpWebRequest      m_HttpWebRequest    = null;
  42.         private string              m_userAgent         = String.Empty;
  43.         private string              m_contentType       = String.Empty;
  44.         private string              m_host              = String.Empty;
  45.         private string              m_encoding          = String.Empty;
  46.         private string              m_referer           = String.Empty;
  47.         private string              m_error             = String.Empty;
  48.         private string              m_origin            = String.Empty;
  49.         private string              m_acceptEncoding    = String.Empty;
  50.         private int                 m_timeout           = 0;
  51.         private int                 m_connectionsLimit  = 0;
  52.         private bool                m_allowAutoRedirect = false ;
  53.         private WebHeaderCollection m_requestHeaders    = null;
  54.        
  55.         // Error Logging Flag
  56.         private bool                m_logOnError        = false;
  57.        
  58.         #endregion
  59.  
  60.         #region ** Public Properties **
  61.        
  62.         // Public Properties
  63.         public HttpWebRequest InternalWebRequest
  64.         {
  65.             set { m_HttpWebRequest = value; }
  66.         }
  67.  
  68.         /// <summary>
  69.         /// UserAgent attribute
  70.         /// Of the HttpWebRequest
  71.         /// </summary>
  72.         public string UserAgent
  73.         {
  74.             get { return m_userAgent;  }
  75.             set { m_userAgent = value; }
  76.         }
  77.  
  78.         /// <summary>
  79.         /// Host attribute
  80.         /// Of the HttpWebRequest
  81.         /// </summary>
  82.         public string Host
  83.         {
  84.             get { return m_host;  }
  85.             set { m_host = value; }
  86.         }
  87.  
  88.         /// <summary>
  89.         /// ContentType attribute
  90.         /// Of the HttpWebRequest
  91.         /// </summary>
  92.         public string ContentType
  93.         {
  94.             get { return m_contentType;  }
  95.             set { m_contentType = value; }
  96.         }
  97.  
  98.         /// <summary>
  99.         /// Encoding parameter
  100.         /// Of the HttpWebRequest
  101.         /// </summary>
  102.         public string Encoding
  103.         {
  104.             get { return m_encoding; }
  105.             set { m_encoding = value; }
  106.         }
  107.  
  108.         /// <summary>
  109.         /// Referer attribute
  110.         /// Of the HttpWebRequest
  111.         /// </summary>
  112.         public string Referer
  113.         {
  114.             get { return m_referer;  }
  115.             set { m_referer = value; }
  116.         }
  117.  
  118.         /// <summary>
  119.         /// Timeout attribute
  120.         /// Of the HttpWebRequest
  121.         /// </summary>
  122.         public int Timeout
  123.         {
  124.             get { return m_timeout;  }
  125.             set { m_timeout = value; }
  126.         }
  127.  
  128.         /// <summary>
  129.         /// ConnectionsLimit
  130.         /// attribute
  131.         /// Of the HttpWebRequest
  132.         /// </summary>
  133.         public int ConnectionsLimit
  134.         {
  135.             get { return m_connectionsLimit;  }
  136.             set { m_connectionsLimit = value; }
  137.         }
  138.  
  139.         /// <summary>
  140.         /// AllowAutoRedirect attribute
  141.         /// Of the HttpWebRequest
  142.         /// </summary>
  143.         public bool AllowAutoRedirect
  144.         {
  145.             get { return m_allowAutoRedirect;  }
  146.             set { m_allowAutoRedirect = value; }
  147.         }
  148.  
  149.         /// <summary>
  150.         /// Origin attribute
  151.         /// Of the HttpWebRequest
  152.         /// </summary>
  153.         public string Origin
  154.         {
  155.             get { return m_origin;  }
  156.             set { m_origin = value; }
  157.         }
  158.  
  159.         /// <summary>
  160.         /// AcceptEncoding
  161.         /// attribute
  162.         /// Of the HttpWebRequest
  163.         /// </summary>
  164.         public string AcceptEncoding
  165.         {
  166.             get { return m_acceptEncoding;  }
  167.             set { m_acceptEncoding = value; }
  168.         }
  169.  
  170.         /// <summary>
  171.         /// Headers attribute
  172.         /// of the HttpWebRequest
  173.         /// </summary>
  174.         public WebHeaderCollection Headers
  175.         {
  176.             get { return m_requestHeaders;  }
  177.             set { m_requestHeaders = value; }
  178.         }
  179.  
  180.         /// <summary>
  181.         /// Message containing the
  182.         /// last error that ocurred.
  183.         /// Can be reseted by using ClearError
  184.         /// Method
  185.         /// </summary>
  186.         public string Error
  187.         {
  188.             get { return m_error; }
  189.         }
  190.        
  191.         /// <summary>
  192.         /// Setter for LogOnError Attribute
  193.         /// </summary>
  194.         public bool LogErrorFlag
  195.         {
  196.             set { m_logOnError = value; }
  197.         }
  198.         #endregion
  199.  
  200.         /// <summary>
  201.         /// Class Constructor
  202.         /// </summary>
  203.         /// <param name="LogOnError">Flag. If true then errors will be logged, else, logging is off</param>
  204.         public WebRequests(bool LogOnError = false)
  205.         {
  206.             m_CookieJar = new CookieContainer();
  207.  
  208.             // Setting Default Values for some Attributes
  209.             m_contentType      = "application/x-www-form-urlencoded";
  210.             m_userAgent        = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1";
  211.             m_encoding         = "ISO-8859-1";
  212.             m_timeout          = 8000;
  213.             m_connectionsLimit = 500;
  214.             m_logOnError       = LogOnError;
  215.             m_requestHeaders   = new WebHeaderCollection();
  216.         }
  217.    
  218.         #region ** Clearing Methods **
  219.  
  220.         /// <summary>
  221.         /// Clear the content of the
  222.         /// Cookie Container class used in
  223.         /// the requests
  224.         /// </summary>
  225.         public void ClearCookies()
  226.         {
  227.             m_CookieJar = new CookieContainer();
  228.         }
  229.  
  230.         /// <summary>
  231.         /// Clears the last error variable
  232.         /// </summary>
  233.         public void ClearError()
  234.         {
  235.             m_error = String.Empty;
  236.         }
  237.  
  238.         #endregion
  239.  
  240.         #region ** HttpWebRequests Methods **
  241.  
  242.         /// <summary>
  243.         /// Executes a Get
  244.         /// creating an HttpWebRequest
  245.         /// object based on previously
  246.         /// set attributes
  247.         /// </summary>
  248.         /// <returns>Response of the Request. Empty string if any error ocurred.</returns>
  249.         public string Get(string url)
  250.         {
  251.             string response = String.Empty;
  252.  
  253.             // Checking for empty url
  254.             if (String.IsNullOrEmpty(url))
  255.             {
  256.                 throw new Exception("URL para o Request não foi configurada ou é nula.");
  257.             }
  258.  
  259.             try
  260.             {
  261.                 // Re-Creating Request Object to avoid exceptions
  262.                 m_HttpWebRequest = WebRequest.Create (url) as HttpWebRequest;
  263.  
  264.                 m_HttpWebRequest.CookieContainer              = m_CookieJar;
  265.                 m_HttpWebRequest.Method                       = "GET";
  266.                 m_HttpWebRequest.UserAgent                    = m_userAgent;
  267.                 m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
  268.                 m_HttpWebRequest.Timeout                      = m_timeout;
  269.                 m_HttpWebRequest.ContentType                  = m_contentType;
  270.                 m_HttpWebRequest.Referer                      = m_referer;
  271.                 m_HttpWebRequest.AllowAutoRedirect            = m_allowAutoRedirect;
  272.  
  273.                 if (!String.IsNullOrEmpty(m_host))
  274.                 {
  275.                     m_HttpWebRequest.Host = m_host;
  276.                 }
  277.  
  278.                 // Execute web request and wait for response
  279.                 using (HttpWebResponse resp = (HttpWebResponse) m_HttpWebRequest.GetResponse())
  280.                 {
  281.                   response= new StreamReader(resp.GetResponseStream()).ReadToEnd();
  282.                 }
  283.             }
  284.             catch (Exception ex)
  285.             {
  286.                 m_error  = ex.ToString();
  287.                 response = String.Empty;
  288.                
  289.                 if (m_logOnError)
  290.                     LogWriter.Error(ex);
  291.             }
  292.  
  293.             return response;
  294.         }
  295.  
  296.         /// <summary>
  297.         /// Executes a POST
  298.         /// creating an HttpWebRequest
  299.         /// object based on previously
  300.         /// set attributes.
  301.         /// </summary>
  302.         /// <param name="postData">Parameters the Post Request</param>
  303.         /// <returns>Response of the Request. Empty string if any error ocurred.</returns>
  304.         public string Post (string url,string postData)
  305.         {
  306.             string response = String.Empty;
  307.  
  308.             // Checking for empty url
  309.             if (String.IsNullOrEmpty(url))
  310.             {
  311.                 throw new Exception("URL para o Request não foi configurada ou é nula.");
  312.             }
  313.  
  314.             try
  315.             {        
  316.                 // Re-Creating Request Object to avoid exceptions
  317.                 m_HttpWebRequest = WebRequest.Create (url) as HttpWebRequest;
  318.  
  319.                 m_HttpWebRequest.Method                       = "POST";
  320.                 m_HttpWebRequest.CookieContainer              = m_CookieJar;
  321.                 m_HttpWebRequest.UserAgent                    = m_userAgent;
  322.                 m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
  323.                 m_HttpWebRequest.Timeout                      = m_timeout;
  324.                 m_HttpWebRequest.ContentType                  = m_contentType;
  325.                 m_HttpWebRequest.Referer                      = m_referer;
  326.                 m_HttpWebRequest.AllowAutoRedirect            = m_allowAutoRedirect;
  327.  
  328.                 if (!String.IsNullOrEmpty(m_host))
  329.                     m_HttpWebRequest.Host = m_host;
  330.  
  331.                 // Counting the bytes to send
  332.                 byte[] bytes                   = System.Text.Encoding.GetEncoding(m_encoding).GetBytes(postData);
  333.                 int bytesSize                  = bytes.Length;
  334.                 m_HttpWebRequest.ContentLength = bytesSize;
  335.  
  336.                 // Send Request
  337.                 using (var requestStream = m_HttpWebRequest.GetRequestStream())
  338.                 {
  339.                     requestStream.Write(bytes, 0, bytesSize);
  340.                 }
  341.  
  342.                 // Get the Response
  343.                 using (WebResponse webResponse = m_HttpWebRequest.GetResponse())
  344.                 {
  345.                     if (webResponse != null)
  346.                     {
  347.                         // Read the Content of the response
  348.                         using (var responseStream = webResponse.GetResponseStream())
  349.                         {
  350.                             using (StreamReader Reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(m_encoding)))
  351.                             {
  352.                                 response = Reader.ReadToEnd().Trim();
  353.                             }
  354.                         }
  355.                     }
  356.                 }
  357.             }
  358.             catch (Exception ex)
  359.             {
  360.                 m_error  = ex.ToString();
  361.                 response = String.Empty;
  362.  
  363.                 if(m_logOnError)
  364.                     LogWriter.Error(ex);
  365.             }
  366.  
  367.             return response;
  368.         }
  369.  
  370.         #endregion
  371.     }
  372. }
Add Comment
Please, Sign In to add comment