添加cookie字符串到 CookieContainer 中


 

補充:

  • webrequest 啟用cookietainer 才能使用cookie;但是未啟用之前可以在http header 中添加cookier字符串讓此次http 有cookie;一旦開啟了cookiecontainer的話,則在http  header 添加cookie無效。

 

  • cookiename和cookievalue 不能有=號,不能name相同,cookiename 和value 不能有空格

         格式: cookiename=cookievalue

 

 

 

 

 

public CookieContainer addCookieToContainer(string cookie,CookieContainer cc,string domian)
      {
          string[] tempCookies = cookie.Split(';');
          string tempCookie = null;
          int Equallength = 0;//  =的位置
          string cookieKey = null;
          string cookieValue = null;
          //qg.gome.com.cn  cookie
          for (int i = 0; i < tempCookies.Length; i++)
          {
              if (!string.IsNullOrEmpty(tempCookies[i]))
              {
                  tempCookie = tempCookies[i];

                  Equallength = tempCookie.IndexOf("=");

                  if (Equallength != -1)       //有可能cookie 無=,就直接一個cookiename;比如:a=3;ck;abc=;
                  {

                      cookieKey = tempCookie.Substring(0, Equallength).Trim();
                      //cookie=

                      if (Equallength == tempCookie.Length - 1)    //這種是等號后面無值,如:abc=;
                      {
                          cookieValue = "";
                      }
                      else
                      {
                          cookieValue = tempCookie.Substring(Equallength + 1, tempCookie.Length - Equallength - 1).Trim();
                      }
                  }

                  else
                  {
                      cookieKey = tempCookie.Trim();
                      cookieValue = "";
                  }

                      cc.Add(new Cookie(cookieKey, cookieValue, "", domain));

              }

          }

          return cc;
      }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM