极品懒人

导航

c#通过文件存储 调用cookies的代码

最近研究paperpass 论文检测系统 登录的时候 考虑到需要把登录信息

 保存下来,但是c#不想php,有这个功能,不能把cookies保存文本,并发送到服务器,所以就写了一段代码

显示 get 的方式获取网页的源代码 1 /// <summary>

 2         /// 获取页面的html代码
 3         /// </summary>
 4         /// <param name="URL">地址</param>
 5         /// <param name="Referer">来路</param>
 6         /// <param name="Cookies">cookies</param>
 7         /// <returns></returns>
 8         protected string getHtml(string URL, string Referer, string CookiesFile ,bool AutoRe)//获取指定地址的源文件
 9         {
10             HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(URL);
11             CookieContainer Cookies = null;
12             if (!String.IsNullOrEmpty(CookiesFile)&&File.Exists(CookiesFile))
13             {
14                 Cookies = getCookieContainer(CookiesFile);
15                
16                 getRequest.CookieContainer = Cookies;
17             }
18             getRequest.Accept = "*/*";
19             getRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1;)";
20             getRequest.KeepAlive = false;
21             getRequest.AllowAutoRedirect = AutoRe;
22             if (!String.IsNullOrEmpty(Referer))
23             {
24                 getRequest.Referer = Referer;
25             }
26             try
27             {
28                 HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
29                 string[] LocationUlr = getResponse.Headers.GetValues("Location");
30 
31                 if (Cookies != null && getResponse.Cookies.Count>0)
32                 {
33                     Cookies.Add(getResponse.Cookies);
34                     //保存Cookies文件
35                     saveCookieContainer(Cookies, CookiesFile);
36                 }
37                 //如果是转向的
38                 if (!AutoRe && LocationUlr != null && LocationUlr.Length > 0)
39                 {
40                     getResponse.Close();
41                     return LocationUlr[0];
42                 }
43                 StreamReader readStream = new StreamReader(getResponse.GetResponseStream(), Encoding.UTF8);
44                 var TheHtml = readStream.ReadToEnd();
45                 readStream.Close(); readStream.Dispose();              
46                 getResponse.Close();
47                 
48                 return TheHtml;
49             }
50             catch (Exception E)
51             {
52                 writeLog(E.ToString(), ownsHttpContext.Server.MapPath("/"));
53                 return null;
54             }
55             finally
56             {
57                 getRequest.Abort();
58             }
59         }

其中的getCookieContainer函数 从文件读取 CookieContainer  ,saveCookieContainer函数把CookieContainer保存到文件!

两个函数如下  /// <summary>

        /// 遍历CookieContainer
        
/// </summary>
        
/// <param name="cc"></param>
        
/// <returns></returns>
        public static List<Cookie> GetAllCookies(CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();

            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
                System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                    | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies) lstCookies.Add(c);
            }
            return lstCookies;
        }
/// <summary>
        
/// 把cookieContainer保存到文件
        
/// </summary>
        
/// <param name="Cookies">需要写入的CookieContainer</param>
        
/// <param name="cookieFile">保存到什么文件</param>
        private static void saveCookieContainer(CookieContainer Cookies, string cookieFile)
        {

            StringBuilder SB = new StringBuilder();
            if (Cookies == null || Cookies.Count == 0) { return; }
            //检测目录是否存在
            if (!File.Exists(cookieFile))
            {
                FileInfo cookieFileInfo = new FileInfo(cookieFile);
                if (!cookieFileInfo.Directory.Exists)
                {
                    cookieFileInfo.Directory.Create();
                }
            }
            List<Cookie> CClist = GetAllCookies(Cookies);
            foreach (Cookie Cookie in CClist)
            {
                SB.AppendFormat("{0}|,|{1}|,|{2}|,|{3}|,|{4}\r\n", Cookie.Name, Cookie.Value, Cookie.Expires.Ticks, Cookie.Domain, Cookie.Path);
            }
            File.WriteAllText(cookieFile, SB.ToString());
        }
        /// <summary>
        
/// 从文件获取cookies
        
/// </summary>
        
/// <param name="cookieFile">cookie保存的文件</param>
        
/// <returns></returns>
        private static CookieContainer getCookieContainer(string cookieFile)
        {
            CookieContainer returnCookieContainer = new CookieContainer();
            if (!File.Exists(cookieFile))
            {
                return returnCookieContainer;
            }
            string[] CookieStrS = File.ReadAllLines(cookieFile);

            foreach (string CookieStr in CookieStrS)
            {
                string[] TempStrS = CookieStr.Split(new string[] { "|,|" }, StringSplitOptions.RemoveEmptyEntries);
                if (TempStrS.Length < 5)
                {
                    continue;
                }
                Cookie CookieTemp = new Cookie();
                CookieTemp.Name = TempStrS[0];
                CookieTemp.Value = TempStrS[1];
                CookieTemp.Expires = new DateTime(Convert.ToInt64(TempStrS[2]));
                CookieTemp.Domain = TempStrS[3];
                CookieTemp.Path = TempStrS[4];
                returnCookieContainer.Add(CookieTemp);
            }
            return returnCookieContainer;
        }
经过测试可以正常使用 ,装载请注明出处 http://www.cnblogs.com/mutuan/

posted on 2012-06-16 18:49  极品懒人  阅读(2906)  评论(0编辑  收藏  举报