博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

带Cookie的 WebClient

Posted on 2015-04-18 00:20  快乐家++  阅读(2305)  评论(0编辑  收藏  举报

 

 

    /// <summary>
    /// WebClient的扩展
    /// </summary>
    public class webClient : WebClient
    {
        /// <summary>是否重定向 默认为true</summary>
        public bool AllowAutoRedirect { get; set; }
        /// <summary>
        ///获取或设置 Referer HTTP 标头的值。默认值为 null。
        /// </summary>
        public string Referer { get; set; }
        /// <summary>
        /// 获取或设置 Content-type HTTP 标头的值。 默认: application/x-www-form-urlencoded
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// 获取或设置 User-agent HTTP 标头的值。默认:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
        /// </summary>
        public string UserAgent { get; set; }

        /// <summary>
        /// 获取或设置 GetResponse 和 GetRequestStream 方法的超时值(以毫秒为单位)。 默认值是 30,000 毫秒(30 秒)。
        /// </summary>
        public int Timeout { get; set; }
        /// <summary>
        /// 获取或设置写入或读取流时的超时(以毫秒为单位)。默认值为 300,000 毫秒(5 分钟)
        /// </summary>
        public int ReadWriteTimeout { get; set; }

        /// <summary>获取或设置请求相关联的Cookie</summary>
        public CookieContainer CookieContainer { get; set; }
        /// <summary>创建一个新的 WebClient 实例。</summary>
        public webClient()
        {
            this.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)";
            this.ContentType = "application/x-www-form-urlencoded";
            this.CookieContainer = new CookieContainer();
            this.AllowAutoRedirect = true;
            this.Timeout = 30 * 1000;
            this.ReadWriteTimeout = 300 * 1000;
        }
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            if (this.Referer != null) request.Referer = this.Referer;
            if (this.ContentType != null) request.ContentType = this.ContentType;
            if (this.UserAgent != null) request.UserAgent = this.UserAgent;
            request.AllowAutoRedirect = this.AllowAutoRedirect;
            request.CookieContainer = this.CookieContainer; //这句很关键,有了他可以保存返回的Cookie
            request.Timeout = this.Timeout;
            request.ReadWriteTimeout = this.ReadWriteTimeout;
            return request;
        }
    }