Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // HttpClient.cs (ver 2)
- // ver 1, at http://www.player.idv.tw/prog/index.php/HttpClient.cs
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Net.Cache;
- using System.Text;
- using System.Web;
- namespace Internet
- {
- public class HttpClient
- {
- private bool _AllowAutoRedirect = false;
- private bool _AllowCookie = false;
- private HttpRequestCachePolicy _CachePolicy = null;
- private string _ContentType;
- private CookieCollection _Cookies = null;
- private ICredentials _Credentials = null;
- private bool _KeepAlive = false;
- private WebProxy _Proxy = null;
- private long[] _Range = null;
- private string _Referer = null;
- private Dictionary<string, string> _RequestHeaders = null;
- private WebHeaderCollection _ResponseHeaders = null;
- private MemoryStream _ResponseStream = null;
- private string _ResponseText = null;
- private HttpStatusCode _StatusCode = HttpStatusCode.OK;
- private Encoding _TextEncoding = null;
- private int _Timeout = 10000;
- private string _UserAgent = null;
- public HttpClient()
- {
- }
- public bool AllowAutoRedirect
- {
- set { _AllowAutoRedirect = value; }
- }
- public bool AllowCookie
- {
- get { return _AllowCookie; }
- set { _AllowCookie = value; }
- }
- public HttpRequestCachePolicy CachePolicy
- {
- set { _CachePolicy = value; }
- }
- public string ContentType
- {
- get { return _ContentType; }
- }
- public CookieCollection Cookies
- {
- get
- {
- if (_AllowCookie)
- return _Cookies;
- return null;
- }
- }
- public ICredentials Credentials
- {
- get { return _Credentials; }
- set { _Credentials = value; }
- }
- public bool KeepAlive
- {
- set { _KeepAlive = value; }
- }
- public string Proxy
- {
- set
- {
- if (string.IsNullOrEmpty(value))
- _Proxy = null;
- else
- _Proxy = new WebProxy(value);
- }
- }
- public string Referer
- {
- set { _Referer = value; }
- }
- public Dictionary<string, string> RequestHeaders
- {
- get
- {
- if (_RequestHeaders == null)
- _RequestHeaders = new Dictionary<string, string>();
- return _RequestHeaders;
- }
- }
- public WebHeaderCollection ResponseHeaders
- {
- get { return _ResponseHeaders; }
- }
- public MemoryStream ResponseStream
- {
- get { return _ResponseStream; }
- }
- public string ResponseText
- {
- get { return _ResponseText; }
- }
- public HttpStatusCode StatusCode
- {
- get { return _StatusCode; }
- }
- public Encoding TextEncoding
- {
- get
- {
- if (_TextEncoding == null)
- _TextEncoding = Encoding.Default;
- return _TextEncoding;
- }
- set { _TextEncoding = value; }
- }
- public int Timeout
- {
- get { return _Timeout; }
- set { _Timeout = value; }
- }
- public string UserAgent
- {
- set { _UserAgent = value; }
- }
- public HttpStatusCode Get(string strUrl)
- {
- try
- {
- Uri uri = new Uri(strUrl);
- HttpWebRequest hwReq = WebRequest.Create(uri) as HttpWebRequest;
- if (_CachePolicy != null)
- hwReq.CachePolicy = _CachePolicy;
- if (_Proxy != null)
- hwReq.Proxy = _Proxy;
- if (_UserAgent != null)
- hwReq.UserAgent = _UserAgent;
- hwReq.Method = "GET";
- hwReq.AllowAutoRedirect = _AllowAutoRedirect;
- hwReq.KeepAlive = _KeepAlive;
- hwReq.Timeout = _Timeout;
- if (_Range != null)
- hwReq.AddRange(_Range[0], _Range[1]);
- if (_Referer != null)
- hwReq.Referer = _Referer;
- // Add authentication to request
- if (_Credentials != null)
- hwReq.Credentials = _Credentials;
- if (_RequestHeaders != null)
- {
- foreach (string key in _RequestHeaders.Keys)
- {
- hwReq.Headers.Add(key, _RequestHeaders[key]);
- }
- }
- if (_AllowCookie)
- hwReq.CookieContainer = new CookieContainer();
- return ProcessRequest(hwReq);
- }
- catch (WebException ex)
- {
- switch (ex.Status)
- {
- case WebExceptionStatus.ProtocolError:
- if (ex.Response != null)
- _StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
- break;
- case WebExceptionStatus.Timeout:
- _StatusCode = HttpStatusCode.RequestTimeout;
- break;
- default:
- throw ex;
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- return _StatusCode;
- }
- public HttpStatusCode Post(string strUrl, Dictionary<string, string> postData)
- {
- try
- {
- Uri uri = new Uri(strUrl);
- HttpWebRequest hwReq = WebRequest.Create(uri) as HttpWebRequest;
- if (_CachePolicy != null)
- hwReq.CachePolicy = _CachePolicy;
- if (_Proxy != null)
- hwReq.Proxy = _Proxy;
- if (_UserAgent != null)
- hwReq.UserAgent = _UserAgent;
- hwReq.Method = "POST";
- hwReq.AllowAutoRedirect = _AllowAutoRedirect;
- hwReq.KeepAlive = _KeepAlive;
- hwReq.Timeout = _Timeout;
- if (_Range != null)
- hwReq.AddRange(_Range[0], _Range[1]);
- hwReq.ContentType = "application/x-www-form-urlencoded";
- if (_Referer != null)
- hwReq.Referer = _Referer;
- // Add authentication to request
- if (_Credentials != null)
- hwReq.Credentials = _Credentials;
- if (_RequestHeaders != null)
- {
- foreach (string key in _RequestHeaders.Keys)
- {
- hwReq.Headers.Add(key, _RequestHeaders[key]);
- }
- }
- if (AllowCookie)
- hwReq.CookieContainer = new CookieContainer();
- StringBuilder data = new StringBuilder();
- string ampersand = "";
- foreach (string key in postData.Keys)
- {
- data.Append(ampersand).Append(key).Append("=").Append(HttpUtility.UrlEncode(postData[key]));
- ampersand = "&";
- }
- byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
- // 設定寫入內容長度
- hwReq.ContentLength = byteData.Length;
- // 寫入 POST 參數
- using (Stream postStream = hwReq.GetRequestStream())
- {
- postStream.Write(byteData, 0, byteData.Length);
- }
- return ProcessRequest(hwReq);
- }
- catch (WebException ex)
- {
- switch (ex.Status)
- {
- case WebExceptionStatus.ProtocolError:
- if (ex.Response != null)
- _StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
- break;
- case WebExceptionStatus.Timeout:
- _StatusCode = HttpStatusCode.RequestTimeout;
- break;
- default:
- throw ex;
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- return _StatusCode;
- }
- public void SetCachePolicy(HttpRequestCacheLevel CacheLevel)
- {
- _CachePolicy = new HttpRequestCachePolicy(CacheLevel);
- }
- public void SetDefaultNetworkCredentials()
- {
- _Credentials = CredentialCache.DefaultNetworkCredentials;
- }
- public void SetDefaultProxy()
- {
- //過時用法?
- //_Proxy = WebProxy.GetDefaultProxy() as WebProxy;
- if (WebRequest.DefaultWebProxy != null)
- {
- WebProxy proxy = WebRequest.DefaultWebProxy as WebProxy;
- if (proxy.Address.AbsoluteUri != string.Empty)
- {
- _Proxy = proxy;
- }
- }
- }
- public void SetNetworkCredential(string username, string password)
- {
- if ((username != null) && (password != null))
- _Credentials = new NetworkCredential(username, password);
- }
- public void SetRange(long from, long to)
- {
- if (from < to)
- _Range = new long[2] { from, to };
- else
- _Range = null;
- }
- private HttpStatusCode ProcessRequest(HttpWebRequest hwReq)
- {
- using (HttpWebResponse hwRes = hwReq.GetResponse() as HttpWebResponse)
- {
- _ContentType = hwRes.ContentType;
- if (_AllowCookie)
- _Cookies = hwRes.Cookies;
- if (hwRes.SupportsHeaders)
- _ResponseHeaders = hwRes.Headers;
- if ((_ContentType != null) && (_ContentType.Substring(0, 4) == "text"))
- {
- _ResponseStream = null;
- using (StreamReader reader = new StreamReader(hwRes.GetResponseStream(), TextEncoding))
- {
- _ResponseText = reader.ReadToEnd();
- }
- }
- else
- {
- _ResponseText = null;
- MemoryStream content = new MemoryStream();
- using (Stream responseStream = hwRes.GetResponseStream())
- {
- responseStream.CopyTo(content);
- }
- _ResponseStream = content;
- }
- }
- _StatusCode = HttpStatusCode.OK;
- return _StatusCode;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement