WebClient保持Session和Cookie

    WebClient不能保持Session和Cookie,但很多情况下需要保持Session和Cookie,经过查看发现只要稍微修改一下就可以达到上述效果。

    我实现了一个HttpWebClient,继承自WebClient,其代码如下:

namespace System.Net
{
    public class HttpWebClient : WebClient
    {
        private CookieContainer cookies;

        public HttpWebClient()
        {
            this.cookies = new CookieContainer();
        }

        public HttpWebClient(CookieContainer cookies)
        {
            this.cookies = cookies;
        }

        public CookieContainer Cookies
        {
            get 
            {
                return this.cookies;
            }
            set
            {
                this.cookies = value;
            }
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            
            if (request is HttpWebRequest)
            {
                HttpWebRequest httpRequest = request as HttpWebRequest;
                httpRequest.CookieContainer = cookies;
            }
            return request;
        }
    }

posted on 2009-08-14 05:05  小橋流水  阅读(569)  评论(0编辑  收藏  举报

导航