Advertisement
p1ayer

HttpClient.cs (ver 2)

Apr 28th, 2015
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.31 KB | None | 0 0
  1. // HttpClient.cs (ver 2)
  2. // ver 1, at http://www.player.idv.tw/prog/index.php/HttpClient.cs
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Net;
  8. using System.Net.Cache;
  9. using System.Text;
  10. using System.Web;
  11.  
  12. namespace Internet
  13. {
  14.     public class HttpClient
  15.     {
  16.         private bool _AllowAutoRedirect = false;
  17.  
  18.         private bool _AllowCookie = false;
  19.  
  20.         private HttpRequestCachePolicy _CachePolicy = null;
  21.  
  22.         private string _ContentType;
  23.  
  24.         private CookieCollection _Cookies = null;
  25.  
  26.         private ICredentials _Credentials = null;
  27.  
  28.         private bool _KeepAlive = false;
  29.  
  30.         private WebProxy _Proxy = null;
  31.  
  32.         private long[] _Range = null;
  33.  
  34.         private string _Referer = null;
  35.  
  36.         private Dictionary<string, string> _RequestHeaders = null;
  37.  
  38.         private WebHeaderCollection _ResponseHeaders = null;
  39.  
  40.         private MemoryStream _ResponseStream = null;
  41.  
  42.         private string _ResponseText = null;
  43.  
  44.         private HttpStatusCode _StatusCode = HttpStatusCode.OK;
  45.  
  46.         private Encoding _TextEncoding = null;
  47.  
  48.         private int _Timeout = 10000;
  49.  
  50.         private string _UserAgent = null;
  51.  
  52.         public HttpClient()
  53.         {
  54.         }
  55.  
  56.         public bool AllowAutoRedirect
  57.         {
  58.             set { _AllowAutoRedirect = value; }
  59.         }
  60.  
  61.         public bool AllowCookie
  62.         {
  63.             get { return _AllowCookie; }
  64.             set { _AllowCookie = value; }
  65.         }
  66.  
  67.         public HttpRequestCachePolicy CachePolicy
  68.         {
  69.             set { _CachePolicy = value; }
  70.         }
  71.  
  72.         public string ContentType
  73.         {
  74.             get { return _ContentType; }
  75.         }
  76.  
  77.         public CookieCollection Cookies
  78.         {
  79.             get
  80.             {
  81.                 if (_AllowCookie)
  82.                     return _Cookies;
  83.                 return null;
  84.             }
  85.         }
  86.  
  87.         public ICredentials Credentials
  88.         {
  89.             get { return _Credentials; }
  90.             set { _Credentials = value; }
  91.         }
  92.  
  93.         public bool KeepAlive
  94.         {
  95.             set { _KeepAlive = value; }
  96.         }
  97.  
  98.         public string Proxy
  99.         {
  100.             set
  101.             {
  102.                 if (string.IsNullOrEmpty(value))
  103.                     _Proxy = null;
  104.                 else
  105.                     _Proxy = new WebProxy(value);
  106.             }
  107.         }
  108.  
  109.         public string Referer
  110.         {
  111.             set { _Referer = value; }
  112.         }
  113.  
  114.         public Dictionary<string, string> RequestHeaders
  115.         {
  116.             get
  117.             {
  118.                 if (_RequestHeaders == null)
  119.                     _RequestHeaders = new Dictionary<string, string>();
  120.                 return _RequestHeaders;
  121.             }
  122.         }
  123.  
  124.         public WebHeaderCollection ResponseHeaders
  125.         {
  126.             get { return _ResponseHeaders; }
  127.         }
  128.  
  129.         public MemoryStream ResponseStream
  130.         {
  131.             get { return _ResponseStream; }
  132.         }
  133.  
  134.         public string ResponseText
  135.         {
  136.             get { return _ResponseText; }
  137.         }
  138.  
  139.         public HttpStatusCode StatusCode
  140.         {
  141.             get { return _StatusCode; }
  142.         }
  143.  
  144.         public Encoding TextEncoding
  145.         {
  146.             get
  147.             {
  148.                 if (_TextEncoding == null)
  149.                     _TextEncoding = Encoding.Default;
  150.                 return _TextEncoding;
  151.             }
  152.             set { _TextEncoding = value; }
  153.         }
  154.  
  155.         public int Timeout
  156.         {
  157.             get { return _Timeout; }
  158.             set { _Timeout = value; }
  159.         }
  160.  
  161.         public string UserAgent
  162.         {
  163.             set { _UserAgent = value; }
  164.         }
  165.  
  166.         public HttpStatusCode Get(string strUrl)
  167.         {
  168.             try
  169.             {
  170.                 Uri uri = new Uri(strUrl);
  171.                 HttpWebRequest hwReq = WebRequest.Create(uri) as HttpWebRequest;
  172.  
  173.                 if (_CachePolicy != null)
  174.                     hwReq.CachePolicy = _CachePolicy;
  175.  
  176.                 if (_Proxy != null)
  177.                     hwReq.Proxy = _Proxy;
  178.  
  179.                 if (_UserAgent != null)
  180.                     hwReq.UserAgent = _UserAgent;
  181.  
  182.                 hwReq.Method = "GET";
  183.                 hwReq.AllowAutoRedirect = _AllowAutoRedirect;
  184.                 hwReq.KeepAlive = _KeepAlive;
  185.                 hwReq.Timeout = _Timeout;
  186.  
  187.                 if (_Range != null)
  188.                     hwReq.AddRange(_Range[0], _Range[1]);
  189.  
  190.                 if (_Referer != null)
  191.                     hwReq.Referer = _Referer;
  192.  
  193.                 // Add authentication to request
  194.                 if (_Credentials != null)
  195.                     hwReq.Credentials = _Credentials;
  196.  
  197.                 if (_RequestHeaders != null)
  198.                 {
  199.                     foreach (string key in _RequestHeaders.Keys)
  200.                     {
  201.                         hwReq.Headers.Add(key, _RequestHeaders[key]);
  202.                     }
  203.                 }
  204.  
  205.                 if (_AllowCookie)
  206.                     hwReq.CookieContainer = new CookieContainer();
  207.  
  208.                 return ProcessRequest(hwReq);
  209.             }
  210.             catch (WebException ex)
  211.             {
  212.                 switch (ex.Status)
  213.                 {
  214.                     case WebExceptionStatus.ProtocolError:
  215.                         if (ex.Response != null)
  216.                             _StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
  217.                         break;
  218.  
  219.                     case WebExceptionStatus.Timeout:
  220.                         _StatusCode = HttpStatusCode.RequestTimeout;
  221.                         break;
  222.  
  223.                     default:
  224.                         throw ex;
  225.                 }
  226.             }
  227.             catch (Exception ex)
  228.             {
  229.                 throw ex;
  230.             }
  231.             return _StatusCode;
  232.         }
  233.  
  234.         public HttpStatusCode Post(string strUrl, Dictionary<string, string> postData)
  235.         {
  236.             try
  237.             {
  238.                 Uri uri = new Uri(strUrl);
  239.                 HttpWebRequest hwReq = WebRequest.Create(uri) as HttpWebRequest;
  240.  
  241.                 if (_CachePolicy != null)
  242.                     hwReq.CachePolicy = _CachePolicy;
  243.  
  244.                 if (_Proxy != null)
  245.                     hwReq.Proxy = _Proxy;
  246.  
  247.                 if (_UserAgent != null)
  248.                     hwReq.UserAgent = _UserAgent;
  249.  
  250.                 hwReq.Method = "POST";
  251.                 hwReq.AllowAutoRedirect = _AllowAutoRedirect;
  252.                 hwReq.KeepAlive = _KeepAlive;
  253.                 hwReq.Timeout = _Timeout;
  254.  
  255.                 if (_Range != null)
  256.                     hwReq.AddRange(_Range[0], _Range[1]);
  257.  
  258.                 hwReq.ContentType = "application/x-www-form-urlencoded";
  259.  
  260.                 if (_Referer != null)
  261.                     hwReq.Referer = _Referer;
  262.  
  263.                 // Add authentication to request
  264.                 if (_Credentials != null)
  265.                     hwReq.Credentials = _Credentials;
  266.  
  267.                 if (_RequestHeaders != null)
  268.                 {
  269.                     foreach (string key in _RequestHeaders.Keys)
  270.                     {
  271.                         hwReq.Headers.Add(key, _RequestHeaders[key]);
  272.                     }
  273.                 }
  274.  
  275.                 if (AllowCookie)
  276.                     hwReq.CookieContainer = new CookieContainer();
  277.  
  278.                 StringBuilder data = new StringBuilder();
  279.                 string ampersand = "";
  280.                 foreach (string key in postData.Keys)
  281.                 {
  282.                     data.Append(ampersand).Append(key).Append("=").Append(HttpUtility.UrlEncode(postData[key]));
  283.                     ampersand = "&";
  284.                 }
  285.  
  286.                 byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
  287.  
  288.                 // 設定寫入內容長度
  289.                 hwReq.ContentLength = byteData.Length;
  290.  
  291.                 // 寫入 POST 參數
  292.                 using (Stream postStream = hwReq.GetRequestStream())
  293.                 {
  294.                     postStream.Write(byteData, 0, byteData.Length);
  295.                 }
  296.  
  297.                 return ProcessRequest(hwReq);
  298.             }
  299.             catch (WebException ex)
  300.             {
  301.                 switch (ex.Status)
  302.                 {
  303.                     case WebExceptionStatus.ProtocolError:
  304.                         if (ex.Response != null)
  305.                             _StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
  306.                         break;
  307.  
  308.                     case WebExceptionStatus.Timeout:
  309.                         _StatusCode = HttpStatusCode.RequestTimeout;
  310.                         break;
  311.  
  312.                     default:
  313.                         throw ex;
  314.                 }
  315.             }
  316.             catch (Exception ex)
  317.             {
  318.                 throw ex;
  319.             }
  320.  
  321.             return _StatusCode;
  322.         }
  323.  
  324.         public void SetCachePolicy(HttpRequestCacheLevel CacheLevel)
  325.         {
  326.             _CachePolicy = new HttpRequestCachePolicy(CacheLevel);
  327.         }
  328.  
  329.         public void SetDefaultNetworkCredentials()
  330.         {
  331.             _Credentials = CredentialCache.DefaultNetworkCredentials;
  332.         }
  333.  
  334.         public void SetDefaultProxy()
  335.         {
  336.             //過時用法?
  337.             //_Proxy = WebProxy.GetDefaultProxy() as WebProxy;
  338.  
  339.             if (WebRequest.DefaultWebProxy != null)
  340.             {
  341.                 WebProxy proxy = WebRequest.DefaultWebProxy as WebProxy;
  342.                 if (proxy.Address.AbsoluteUri != string.Empty)
  343.                 {
  344.                     _Proxy = proxy;
  345.                 }
  346.             }
  347.         }
  348.  
  349.         public void SetNetworkCredential(string username, string password)
  350.         {
  351.             if ((username != null) && (password != null))
  352.                 _Credentials = new NetworkCredential(username, password);
  353.         }
  354.  
  355.         public void SetRange(long from, long to)
  356.         {
  357.             if (from < to)
  358.                 _Range = new long[2] { from, to };
  359.             else
  360.                 _Range = null;
  361.         }
  362.         private HttpStatusCode ProcessRequest(HttpWebRequest hwReq)
  363.         {
  364.             using (HttpWebResponse hwRes = hwReq.GetResponse() as HttpWebResponse)
  365.             {
  366.                 _ContentType = hwRes.ContentType;
  367.                 if (_AllowCookie)
  368.                     _Cookies = hwRes.Cookies;
  369.                 if (hwRes.SupportsHeaders)
  370.                     _ResponseHeaders = hwRes.Headers;
  371.  
  372.                 if ((_ContentType != null) && (_ContentType.Substring(0, 4) == "text"))
  373.                 {
  374.                     _ResponseStream = null;
  375.                     using (StreamReader reader = new StreamReader(hwRes.GetResponseStream(), TextEncoding))
  376.                     {
  377.                         _ResponseText = reader.ReadToEnd();
  378.                     }
  379.                 }
  380.                 else
  381.                 {
  382.                     _ResponseText = null;
  383.                     MemoryStream content = new MemoryStream();
  384.                     using (Stream responseStream = hwRes.GetResponseStream())
  385.                     {
  386.                         responseStream.CopyTo(content);
  387.                     }
  388.                     _ResponseStream = content;
  389.                 }
  390.             }
  391.             _StatusCode = HttpStatusCode.OK;
  392.             return _StatusCode;
  393.         }
  394.     }
  395. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement