1. 程式人生 > >C# Http網路訪問類

C# Http網路訪問類

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace HttpClient
{

    /// <summary>
    /// 通過Http協議訪問Web
    /// </summary>
    public class HttpClient
    {
        #region Cookie集合
        /// <summary>
        /// Cookie集合
        /// </summary>
        private CookieContainer cookies;
        #endregion

        #region Http user-agent標頭值
        /// <summary>
        /// Http user-agent標頭值
        /// </summary>
        public string UserAgent { get; set; }
        #endregion

        #region HttpClient建構函式
        public HttpClient()
        {
            this.cookies = new CookieContainer();
        }
        #endregion 

        #region 獲取HttpClient的Cookie集合
        /// <summary>
        /// 獲取HttpClient的Cookie集合
        /// </summary>
        /// <returns></returns>
        public CookieContainer GetCookieContainer()
        {
            return this.cookies;
        }
        #endregion

        #region 設定HttpClient的Cookie集合
        /// <summary>
        /// 設定HttpClient的Cookie集合
        /// </summary>
        /// <param name="_cookie">Cookie集合物件</param>
        /// <returns>True設定成功 False設定失敗</returns>
        public bool SetCookieContainer(CookieContainer _cookie)
        {
            if (_cookie != null)
            {
                this.cookies = _cookie;
                return true;
            }
            return false;
        }
        #endregion

        #region 以GET方式開啟一個Http連線
        /// <summary>
        /// 以GET方式開啟一個Http連線
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <returns></returns>
        public ResultResponse OpenGetUrl(string url, Dictionary<string, string> headers)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this.cookies;
            request.Method = HttpClient.ConnectionType.GET;
            request.KeepAlive = true;
            if (this.UserAgent != null && this.UserAgent != "")
            {
                request.UserAgent = this.UserAgent;
            }
            this.FillHeaders(request, headers);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            return new ResultResponse(response);
        }
        #endregion

        #region 以GET方式開啟一個Http連線,302自定義處理行為
        /// <summary>
        /// 以GET方式開啟一個Http連線,302自定義處理行為
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <param name="action">302跳轉處理</param>
        /// <returns></returns>
        public ResultResponse OpenGetUrlRedirect(string url, Dictionary<string, string> headers,HttpClient.RedirectAction action)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this.cookies;
            request.Method = HttpClient.ConnectionType.GET;
            request.KeepAlive = true;
            request.AllowAutoRedirect = false; //302不採用預設行為處理
            if (this.UserAgent != null && this.UserAgent != "")
            {
                request.UserAgent = this.UserAgent;
            }
            this.FillHeaders(request, headers);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            ResultResponse result=new ResultResponse(response);
            if (response.StatusCode == HttpStatusCode.Found)
            {
                bool ret = true;
                if (action != null)
                {
                    ret = action(result);
                }
                string locationurl = response.Headers["Location"];
                if (ret == true)
                {
                    return this.OpenGetUrlRedirect(locationurl, null, action);
                }
                return result;
            }
            return result;
        }
        #endregion

        #region Http 302跳轉處理
        /// <summary>
        /// Http 302跳轉處理
        /// </summary>
        /// <param name="result">響應物件</param>
        /// <returns>False 不繼續跳轉 True繼續跳轉</returns>
        public delegate bool RedirectAction(ResultResponse result);
        #endregion

        #region 將Http標頭值新增到Request物件中
        /// <summary>
        /// 將Http標頭值新增到Request物件中
        /// </summary>
        /// <param name="headers"></param>
        private void FillHeaders(HttpWebRequest request,Dictionary<string, string> headers)
        {
            if (headers != null && headers.Count > 0)
            {
                Dictionary<string, string>.Enumerator em = headers.GetEnumerator();
                while (em.MoveNext())
                {
                    request.Headers.Add(em.Current.Key, em.Current.Value);
                }
            }
        }
        #endregion

        #region 以POST方式開啟一個Http連線
        /// <summary>
        /// 以POST方式開啟一個Http連線
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <param name="data">傳送的資料</param>
        /// <returns></returns>
        public ResultResponse OpenPostUrl(string url,Dictionary<string,string> headers,Dictionary<string,string> data)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this.cookies;
            request.Method = HttpClient.ConnectionType.POST;
            request.KeepAlive = true;
            if (this.UserAgent != null && this.UserAgent != "")
            {
                request.UserAgent = this.UserAgent;
            }
            this.FillHeaders(request, headers);
            byte[] buff = DictToBytes(data);
            request.GetRequestStream().Write(buff, 0, buff.Length);
            request.GetRequestStream().Close();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            return new ResultResponse(response);
        }
        #endregion

        #region 以POST方式開啟一個Http連線,302自定義處理行為
        /// <summary>
        /// 以POST方式開啟一個Http連線,302自定義處理行為
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <param name="data">傳送的資料</param>
        /// <param name="action">302自定義處理</param>
        /// <returns></returns>
        public ResultResponse OpenPostUrlRedirect(string url, Dictionary<string, string> headers, Dictionary<string, string> data,HttpClient.RedirectAction action)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = this.cookies;
            request.Method = HttpClient.ConnectionType.POST;
            request.KeepAlive = true;
            request.AllowAutoRedirect = false;
            if (this.UserAgent != null && this.UserAgent != "")
            {
                request.UserAgent = this.UserAgent;
            }
            this.FillHeaders(request, headers);
            byte[] buff = DictToBytes(data);
            request.GetRequestStream().Write(buff, 0, buff.Length);
            request.GetRequestStream().Close();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            ResultResponse result = new ResultResponse(response);

            if (response.StatusCode == HttpStatusCode.Found)
            {
                bool ret = true;
                if (action != null)
                {
                    ret = action(result);
                }
                string locationurl = response.Headers["Location"];
                return result;
            }
            return result;
        }
        #endregion

        #region 將字典的key和value拼接成http引數
        /// <summary>
        /// 將字典的key和value拼接成http引數
        /// </summary>
        /// <param name="dic">引數</param>
        /// <returns></returns>
        private byte[] DictToBytes(Dictionary<string, string> dic)
        {
            StringBuilder sb = null;
            if (dic != null)
            {
                Dictionary<string,string>.Enumerator em= dic.GetEnumerator();
                sb = new StringBuilder();
                while (em.MoveNext())
                {
                    sb.Append(String.Format("{0}={1}&", em.Current.Key, em.Current.Value));
                }
                return System.Text.Encoding.UTF8.GetBytes(sb.ToString());
            }
            return null;
        }
        #endregion

        #region HttpClient開啟連線的方式
        /// <summary>
        /// HttpClient開啟連線的方式
        /// </summary>
        public static class ConnectionType
        {
            public static string GET { get { return "GET"; } }
            public static string POST { get { return "POST"; } }
        }
        #endregion




    }
}
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace HttpClient
{

    /// <summary>
    ///包含伺服器響應資料的物件
    /// </summary>
    public class ResultResponse
    {
        #region HttpWebResponse物件
        /// <summary>
        /// HttpWebResponse物件
        /// </summary>
        private HttpWebResponse m_response;
        #endregion

        #region 建立一個HttpWebResponse物件
        /// <summary>
        /// 建立一個HttpWebResponse物件
        /// </summary>
        /// <param name="_response">HttpWebResponse</param>
        public ResultResponse(HttpWebResponse _response)
        {
            this.m_response = _response;
        }
        #endregion

        #region 獲取響應內容的二進位制流
        /// <summary>
        /// 獲取響應內容的二進位制流 
        /// </summary>
        /// <returns></returns>
        public Stream GetResponseStream()
        {
            if (this.m_response != null)
            {
                return this.m_response.GetResponseStream();
            }
            return null;
        }
        #endregion

        #region Http版本
        /// <summary>
        /// Http版本
        /// </summary>
        public string ProtocolVersion { get { return this.m_response != null ? this.m_response.ProtocolVersion.ToString() : ""; } }
        #endregion
        /// <summary>
        /// 響應方法
        /// </summary>
        public string Method { get { return this.m_response != null ? this.m_response.Method : ""; } }
        /// <summary>
        /// Http狀態碼
        /// </summary>
        public string StatusCode { get { return this.m_response != null ? this.m_response.StatusCode.ToString() : ""; } }
        /// <summary>
        /// Http響應頭
        /// </summary>
        public WebHeaderCollection Headers { get { return this.m_response != null ? this.m_response.Headers : null;} }

        /// <summary>
        /// 響應流的字元編碼
        /// </summary>
        /// <returns></returns>
        public Encoding getResponseEncoding()
        {
            if (this.m_response != null)
            {
                return Encoding.GetEncoding(this.m_response.ContentEncoding);
            }
            return null;
        }

        /// <summary>
        /// 獲取響應內容的字串
        /// </summary>
        /// <param name="encoding">字串編碼(預設utf8)</param>
        /// <returns></returns>
        public string GetContent(string encoding="utf-8")
        {
            return System.Text.Encoding.GetEncoding(encoding).GetString(this.StreamtoBytes(this.GetResponseStream()));
        }

        /// <summary>
        /// 獲取原始的HttpWebResponse
        /// </summary>
        /// <returns></returns>
        public HttpWebResponse GetRawResponse()
        {
            return this.m_response;
        }

        /// <summary>
        /// 二進位制流轉換成位元組陣列
        /// </summary>
        /// <param name="_stream"></param>
        /// <returns></returns>
        private byte[] StreamtoBytes(Stream _stream)
        {
            byte[] buff;
            int rlen;
            MemoryStream _ms;
            if (_stream != null)
            {
                buff = new byte[1024];
                rlen = 0;
                _ms = new MemoryStream();
                while ((rlen = _stream.Read(buff, 0, 1024)) > 0)
                {
                    _ms.Write(buff, 0, rlen);
                }
                buff = _ms.ToArray();
                _ms.Close();
                _ms.Dispose();
                return buff;
            }
            return null;
        }
    }
}