Advertisement
MarcelloGrechi

WebRequests Library C#

Jan 3rd, 2013
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 20.98 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 System.Drawing;
  32. using System.Net.Security;
  33.  
  34. namespace WebUtilsLib
  35. {
  36.     public class WebRequests
  37.     {
  38.         #region ** Private Attributes **
  39.  
  40.         // Private Attributes
  41.         private WebProxy            m_proxy             = null;        
  42.         private CookieContainer     m_cookieJar         = null;
  43.         private HttpWebRequest      m_HttpWebRequest    = null;
  44.         private string              m_userAgent         = String.Empty;
  45.         private string              m_contentType       = String.Empty;
  46.         private string              m_host              = String.Empty;
  47.         private string              m_encoding          = String.Empty;
  48.         private string              m_referer           = String.Empty;
  49.         private string              m_error             = String.Empty;
  50.         private string              m_origin            = String.Empty;
  51.         private string              m_accept            = String.Empty;        
  52.         private int                 m_timeout           = 0;
  53.         private int                 m_readWriteTimeout  = 0;
  54.         private int                 m_connectionsLimit  = 0;
  55.         private bool                m_allowAutoRedirect = false;
  56.         private bool                m_keepAlive         = true;
  57.         private WebHeaderCollection m_requestHeaders    = null;        
  58.        
  59.         #endregion
  60.  
  61.         #region ** Public Properties **
  62.        
  63.         public CookieContainer CookieJar
  64.         {
  65.             get { return m_cookieJar; }
  66.         }
  67.  
  68.         // Public Properties
  69.         public HttpWebRequest InternalWebRequest
  70.         {
  71.             set { m_HttpWebRequest = value; }
  72.         }
  73.  
  74.         /// <summary>
  75.         /// UserAgent attribute
  76.         /// Of the HttpWebRequest
  77.         /// </summary>
  78.         public string UserAgent
  79.         {
  80.             get { return m_userAgent;  }
  81.             set { m_userAgent = value; }
  82.         }
  83.  
  84.         /// <summary>
  85.         /// Accept attribute
  86.         /// Of the HttpWebRequest
  87.         /// </summary>
  88.         public string Accept
  89.         {
  90.             get { return m_accept; }
  91.             set { m_accept = value; }
  92.         }
  93.  
  94.         /// <summary>
  95.         /// Connection KeepAlive attribute
  96.         /// Of the HttpWebRequest
  97.         /// </summary>
  98.         public bool KeepAlive
  99.         {
  100.             get { return m_keepAlive; }
  101.             set { m_keepAlive = value; }
  102.         }
  103.  
  104.         /// <summary>
  105.         /// WebProxy attribute
  106.         /// </summary>
  107.         public WebProxy Proxy
  108.         {
  109.             get { return m_proxy; }
  110.             set { m_proxy = value; }
  111.         }
  112.  
  113.         /// <summary>
  114.         /// Host attribute
  115.         /// Of the HttpWebRequest
  116.         /// </summary>
  117.         public string Host
  118.         {
  119.             get { return m_host;  }
  120.             set { m_host = value; }
  121.         }
  122.  
  123.         /// <summary>
  124.         /// ContentType attribute
  125.         /// Of the HttpWebRequest
  126.         /// </summary>
  127.         public string ContentType
  128.         {
  129.             get { return m_contentType;  }
  130.             set { m_contentType = value; }
  131.         }
  132.  
  133.         /// <summary>
  134.         /// Encoding parameter
  135.         /// Of the HttpWebRequest
  136.         /// </summary>
  137.         public string Encoding
  138.         {
  139.             get { return m_encoding; }
  140.             set { m_encoding = value; }
  141.         }
  142.  
  143.         /// <summary>
  144.         /// Referer attribute
  145.         /// Of the HttpWebRequest
  146.         /// </summary>
  147.         public string Referer
  148.         {
  149.             get { return m_referer;  }
  150.             set { m_referer = value; }
  151.         }
  152.  
  153.         /// <summary>
  154.         /// Timeout attribute
  155.         /// Of the HttpWebRequest
  156.         /// </summary>
  157.         public int Timeout
  158.         {
  159.             get { return m_timeout;  }
  160.             set { m_timeout = value; }
  161.         }
  162.  
  163.         /// <summary>
  164.         /// Read Write Timeout attribute
  165.         /// Of the HttpWebRequest
  166.         /// </summary>
  167.         public int ReadWriteTimeout
  168.         {
  169.             get { return m_readWriteTimeout; }
  170.             set { m_readWriteTimeout = value; }
  171.         }        
  172.  
  173.         /// <summary>
  174.         /// ConnectionsLimit
  175.         /// attribute
  176.         /// Of the HttpWebRequest
  177.         /// </summary>
  178.         public int ConnectionsLimit
  179.         {
  180.             get { return m_connectionsLimit;  }
  181.             set { m_connectionsLimit = value; }
  182.         }
  183.  
  184.         /// <summary>
  185.         /// AllowAutoRedirect attribute
  186.         /// Of the HttpWebRequest
  187.         /// </summary>
  188.         public bool AllowAutoRedirect
  189.         {
  190.             get { return m_allowAutoRedirect;  }
  191.             set { m_allowAutoRedirect = value; }
  192.         }
  193.  
  194.         /// <summary>
  195.         /// Origin attribute
  196.         /// Of the HttpWebRequest
  197.         /// </summary>
  198.         public string Origin
  199.         {
  200.             get { return m_origin;  }
  201.             set { m_origin = value; }
  202.         }
  203.  
  204.         /// <summary>
  205.         /// Headers attribute
  206.         /// of the HttpWebRequest
  207.         /// </summary>
  208.         public WebHeaderCollection Headers
  209.         {
  210.             get { return m_requestHeaders;  }
  211.             set { m_requestHeaders = value; }
  212.         }
  213.  
  214.         /// <summary>
  215.         /// Message containing the
  216.         /// last error that ocurred.
  217.         /// Can be reseted by using ClearError
  218.         /// Method
  219.         /// </summary>
  220.         public string Error
  221.         {
  222.             get { return m_error; }
  223.         }
  224.        
  225.         #endregion
  226.  
  227.         #region ** Class Constructor **
  228.  
  229.         /// <summary>
  230.         /// Class Constructor
  231.         /// </summary>
  232.         /// <param name="LogOnError">Flag. If true then errors will be logged, else, logging is off</param>
  233.         public WebRequests()
  234.         {
  235.             m_cookieJar = new CookieContainer();
  236.  
  237.             // Setting Default Values for some Attributes
  238.             m_contentType       = "application/x-www-form-urlencoded";
  239.             m_userAgent         = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1";
  240.             m_encoding          = "ISO-8859-1";
  241.             m_timeout           = 8000;
  242.             m_readWriteTimeout  = 8000;
  243.             m_connectionsLimit  = 500;
  244.             m_allowAutoRedirect = true;
  245.             m_requestHeaders    = new WebHeaderCollection();
  246.         }
  247.  
  248.         #endregion
  249.    
  250.         #region ** Clearing and Configuration Methods Methods **
  251.  
  252.         /// <summary>
  253.         /// Clear the content of the
  254.         /// Cookie Container class used in
  255.         /// the requests
  256.         /// </summary>
  257.         public void ClearCookies()
  258.         {
  259.             m_cookieJar = new CookieContainer();
  260.         }
  261.  
  262.         /// <summary>
  263.         /// Clears the last error variable
  264.         /// </summary>
  265.         public void ClearError()
  266.         {
  267.             m_error = String.Empty;
  268.         }
  269.  
  270.         /// <summary>
  271.         /// Ignored any certificate validation issued by the request.
  272.         /// This usually solves Validation/Authentication errors
  273.         /// such as "access denied" or "Forbidden"
  274.         /// </summary>
  275.         public void TurnOffCertificateValidator ()
  276.         {
  277.             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback (delegate { return true; });
  278.         }
  279.  
  280.         #endregion
  281.  
  282.         #region ** HttpWebRequests Methods **
  283.  
  284.         /// <summary>
  285.         /// Executes a Get
  286.         /// creating an HttpWebRequest
  287.         /// object based on previously
  288.         /// set attributes
  289.         /// </summary>
  290.         /// <returns>Response of the Request. Empty string if any error ocurred.</returns>
  291.         public string Get (string url, bool throwOnError = false)
  292.         {
  293.             string response = String.Empty;
  294.  
  295.             // Checking for empty url
  296.             if (String.IsNullOrEmpty(url))
  297.             {
  298.                 throw new Exception("URL para o Request não foi configurada ou é nula.");
  299.             }
  300.  
  301.             try
  302.             {
  303.                 // Re-Creating Request Object to avoid exceptions
  304.                 m_HttpWebRequest = WebRequest.Create (url) as HttpWebRequest;
  305.  
  306.                 // Proxy
  307.                 if (m_proxy != null)
  308.                     m_HttpWebRequest.Proxy = m_proxy;
  309.                 // Headers
  310.                 if (m_requestHeaders != null)
  311.                     m_HttpWebRequest.Headers = m_requestHeaders;
  312.                
  313.                 m_HttpWebRequest.AutomaticDecompression       = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None;
  314.                 m_HttpWebRequest.CookieContainer              = m_cookieJar;
  315.                 m_HttpWebRequest.Method                       = "GET";
  316.                 m_HttpWebRequest.UserAgent                    = m_userAgent;
  317.                 m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
  318.                 m_HttpWebRequest.Timeout                      = m_timeout;
  319.                 m_HttpWebRequest.ReadWriteTimeout             = m_readWriteTimeout;
  320.                 m_HttpWebRequest.ContentType                  = m_contentType;
  321.                 m_HttpWebRequest.Referer                      = m_referer;
  322.                 m_HttpWebRequest.AllowAutoRedirect            = m_allowAutoRedirect;
  323.                 m_HttpWebRequest.Accept                       = m_accept;
  324.                 m_HttpWebRequest.KeepAlive                    = m_keepAlive;
  325.                
  326.                 if (!String.IsNullOrEmpty(m_host))
  327.                 {
  328.                     m_HttpWebRequest.Host = m_host;
  329.                 }
  330.  
  331.                 // Execute web request and wait for response
  332.                 using (HttpWebResponse resp = (HttpWebResponse) m_HttpWebRequest.GetResponse())
  333.                 {
  334.                     using (var stream = resp.GetResponseStream ())
  335.                     {
  336.                         using (var reader = new StreamReader (stream))
  337.                         {
  338.                             response = reader.ReadToEnd ();
  339.                         }
  340.                     }
  341.                 }
  342.             }
  343.             catch (Exception ex)
  344.             {
  345.                 m_error  = ex.ToString();
  346.                 if (throwOnError)
  347.                     throw ex;
  348.             }
  349.  
  350.             return response;
  351.         }
  352.  
  353.         /// <summary>
  354.         /// Gets the stream        
  355.         /// </summary>
  356.         /// <param name="url">The URL.</param>        
  357.         /// <returns>True if no error ocurred</returns>
  358.         public byte[] GetBytes (string url, bool throwOnError = false)
  359.         {
  360.             // Checking for empty url
  361.             if (String.IsNullOrEmpty(url))
  362.             {
  363.                 throw new Exception("URL para o Request não foi configurada ou é nula.");
  364.             }
  365.  
  366.             try
  367.             {
  368.                 // Re-Creating Request Object to avoid exceptions
  369.                 m_HttpWebRequest = WebRequest.Create(url) as HttpWebRequest;
  370.  
  371.                 // Proxy
  372.                 if (m_proxy != null)
  373.                     m_HttpWebRequest.Proxy = m_proxy;
  374.                 // Headers
  375.                 if (m_requestHeaders != null)
  376.                     m_HttpWebRequest.Headers = m_requestHeaders;
  377.  
  378.                 m_HttpWebRequest.AutomaticDecompression       = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None;
  379.                 m_HttpWebRequest.CookieContainer              = m_cookieJar;
  380.                 m_HttpWebRequest.Method                       = "GET";
  381.                 m_HttpWebRequest.UserAgent                    = m_userAgent;
  382.                 m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
  383.                 m_HttpWebRequest.Timeout                      = m_timeout;
  384.                 m_HttpWebRequest.ReadWriteTimeout             = m_readWriteTimeout;
  385.                 m_HttpWebRequest.ContentType                  = m_contentType;
  386.                 m_HttpWebRequest.Referer                      = m_referer;
  387.                 m_HttpWebRequest.AllowAutoRedirect            = m_allowAutoRedirect;
  388.                 m_HttpWebRequest.Accept                       = m_accept;
  389.                 m_HttpWebRequest.KeepAlive                    = m_keepAlive;
  390.  
  391.                 if (!String.IsNullOrEmpty(m_host))
  392.                 {
  393.                     m_HttpWebRequest.Host = m_host;
  394.                 }
  395.  
  396.                 // Execute web request and wait for response
  397.                 using (HttpWebResponse resp = (HttpWebResponse)m_HttpWebRequest.GetResponse ())
  398.                 {                                        
  399.                     // Reading response
  400.                     using (MemoryStream ms = new MemoryStream ())
  401.                     {
  402.                         using (var stream = resp.GetResponseStream ())
  403.                         {
  404.                             stream.CopyTo (ms);
  405.                             return ms.ToArray ();
  406.                         }
  407.                     }
  408.                 }
  409.             }
  410.             catch (Exception ex)
  411.             {
  412.                 m_error = ex.ToString();
  413.                 if (throwOnError)
  414.                     throw ex;
  415.             }
  416.  
  417.             return null;
  418.         }
  419.  
  420.         /// <summary>
  421.         /// Gets the web response
  422.         /// as a Bitmap
  423.         /// </summary>
  424.         /// <param name="url">The URL.</param>
  425.         /// <returns>Bitmap response of the web request</returns>
  426.         public Bitmap GetBitmap (string url, bool throwOnError = false)
  427.         {
  428.             Bitmap response = null;
  429.  
  430.             // Checking for empty url
  431.             if (String.IsNullOrEmpty(url))
  432.             {
  433.                 throw new Exception("URL para o Request não foi configurada ou é nula.");
  434.             }
  435.  
  436.             try
  437.             {
  438.                 // Re-Creating Request Object to avoid exceptions
  439.                 m_HttpWebRequest = WebRequest.Create(url) as HttpWebRequest;
  440.  
  441.                 // Proxy
  442.                 if (m_proxy != null)
  443.                     m_HttpWebRequest.Proxy = m_proxy;
  444.                 // Headers
  445.                 if (m_requestHeaders != null)
  446.                     m_HttpWebRequest.Headers = m_requestHeaders;                
  447.                
  448.                 m_HttpWebRequest.AutomaticDecompression       = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None;
  449.                 m_HttpWebRequest.CookieContainer              = m_cookieJar;
  450.                 m_HttpWebRequest.Method                       = "GET";
  451.                 m_HttpWebRequest.UserAgent                    = m_userAgent;
  452.                 m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
  453.                 m_HttpWebRequest.Timeout                      = m_timeout;
  454.                 m_HttpWebRequest.ReadWriteTimeout             = m_readWriteTimeout;
  455.                 m_HttpWebRequest.ContentType                  = m_contentType;
  456.                 m_HttpWebRequest.Referer                      = m_referer;
  457.                 m_HttpWebRequest.AllowAutoRedirect            = m_allowAutoRedirect;
  458.                 m_HttpWebRequest.Accept                       = m_accept;
  459.                 m_HttpWebRequest.KeepAlive                    = m_keepAlive;
  460.  
  461.                 if (!String.IsNullOrEmpty(m_host))
  462.                 {
  463.                     m_HttpWebRequest.Host = m_host;
  464.                 }
  465.  
  466.                 // Execute web request and wait for response
  467.                 using (HttpWebResponse resp = (HttpWebResponse)m_HttpWebRequest.GetResponse())
  468.                 {
  469.                     using (var stream = resp.GetResponseStream ())
  470.                     {
  471.                         response = new Bitmap(stream);
  472.                     }
  473.                 }
  474.             }
  475.             catch (Exception ex)
  476.             {
  477.                 m_error = ex.ToString();
  478.                 if (throwOnError)
  479.                     throw ex;
  480.             }
  481.  
  482.             return response;
  483.         }
  484.  
  485.  
  486.         /// <summary>
  487.         /// Executes a POST
  488.         /// creating an HttpWebRequest
  489.         /// object based on previously
  490.         /// set attributes.
  491.         /// </summary>
  492.         /// <param name="postData">Parameters the Post Request</param>
  493.         /// <returns>Response of the Request. Empty string if any error ocurred.</returns>
  494.         public string Post (string url,string postData, bool throwOnError = false)
  495.         {
  496.             string response = String.Empty;
  497.  
  498.             // Checking for empty url
  499.             if (String.IsNullOrEmpty(url))
  500.             {
  501.                 throw new Exception("URL para o Request não foi configurada ou é nula.");
  502.             }
  503.  
  504.             try
  505.             {        
  506.                 // Re-Creating Request Object to avoid exceptions
  507.                 m_HttpWebRequest = WebRequest.Create (url) as HttpWebRequest;
  508.  
  509.                 // Proxy
  510.                 if (m_proxy != null)
  511.                     m_HttpWebRequest.Proxy = m_proxy;
  512.                 // Headers
  513.                 if (m_requestHeaders != null)
  514.                     m_HttpWebRequest.Headers = m_requestHeaders;
  515.  
  516.                 m_HttpWebRequest.AutomaticDecompression       = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None;
  517.                 m_HttpWebRequest.Method                       = "POST";
  518.                 m_HttpWebRequest.CookieContainer              = m_cookieJar;
  519.                 m_HttpWebRequest.UserAgent                    = m_userAgent;
  520.                 m_HttpWebRequest.ServicePoint.ConnectionLimit = m_connectionsLimit;
  521.                 m_HttpWebRequest.Timeout                      = m_timeout;
  522.                 m_HttpWebRequest.ReadWriteTimeout             = m_readWriteTimeout;
  523.                 m_HttpWebRequest.ContentType                  = m_contentType;
  524.                 m_HttpWebRequest.Referer                      = m_referer;
  525.                 m_HttpWebRequest.AllowAutoRedirect            = m_allowAutoRedirect;
  526.                 m_HttpWebRequest.Accept                       = m_accept;                
  527.                 m_HttpWebRequest.KeepAlive                    = m_keepAlive;
  528.  
  529.                 if (!String.IsNullOrEmpty(m_host))
  530.                     m_HttpWebRequest.Host = m_host;
  531.  
  532.                 // Counting the bytes to send
  533.                 byte[] bytes                   = System.Text.Encoding.GetEncoding(m_encoding).GetBytes(postData);
  534.                 int bytesSize                  = bytes.Length;
  535.                 m_HttpWebRequest.ContentLength = bytesSize;
  536.  
  537.                 // Send Request
  538.                 using (var requestStream = m_HttpWebRequest.GetRequestStream())
  539.                 {
  540.                     requestStream.Write(bytes, 0, bytesSize);
  541.                 }
  542.  
  543.                 // Get the Response
  544.                 using (WebResponse webResponse = m_HttpWebRequest.GetResponse())
  545.                 {
  546.                     if (webResponse != null)
  547.                     {
  548.                         // Read the Content of the response
  549.                         using (var responseStream = webResponse.GetResponseStream())
  550.                         {
  551.                             using (StreamReader reader = new StreamReader(responseStream))
  552.                             {
  553.                                 response = reader.ReadToEnd().Trim();
  554.                             }
  555.                         }
  556.                     }
  557.                 }
  558.             }
  559.             catch (Exception ex)
  560.             {
  561.                 m_error  = ex.ToString();
  562.                 response = String.Empty;
  563.                 if (throwOnError)
  564.                     throw ex;
  565.             }
  566.  
  567.             return response;
  568.         }
  569.  
  570.         #endregion
  571.  
  572.     }
  573. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement