当前位置: 首页>>代码示例>>C#>>正文


C# Net.CookieContainer类代码示例

本文整理汇总了C#中System.Net.CookieContainer的典型用法代码示例。如果您正苦于以下问题:C# CookieContainer类的具体用法?C# CookieContainer怎么用?C# CookieContainer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


CookieContainer类属于System.Net命名空间,在下文中一共展示了CookieContainer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendLoginData

        private async Task<bool> SendLoginData(string username, string password)
        {
            CookieContainer cookies = await _webManager.PostData(
                Constants.LOGIN_URL, string.Format(
                    "action=login&username={0}&password={1}",
                    username.Replace(" ", "+"),
                    WebUtility.UrlEncode(password)));

            if (cookies.Count < 2)
            {
                return false;
            }

            var fixedCookieContainer = new CookieContainer();

            // TODO: HUGE HACK. For some reason Windows Phone does not use the Domain Key on a cookie, but only the domain when making requests.
            // Windows 8 won't break on it, but Windows Phone will, since the Domain Key and Domain are different on SA.
            // We need to move this code to a more common place.

            foreach (Cookie cookie in cookies.GetCookies(new Uri(Constants.COOKIE_DOMAIN_URL)))
            {
                var fixedCookie = new Cookie(cookie.Name, cookie.Value, "/", ".somethingawful.com");
                fixedCookieContainer.Add(new Uri(Constants.COOKIE_DOMAIN_URL), fixedCookie);
            }

            await _localStorageManager.SaveCookie(Constants.COOKIE_FILE, cookies, new Uri(Constants.COOKIE_DOMAIN_URL));
            return true;
        }
开发者ID:Gluco,项目名称:AwfulMetro,代码行数:28,代码来源:AuthenticationManager.cs

示例2: Transfer

		/// <summary>
		/// Access specified url.
		/// </summary>
		/// <returns></returns>
		public static TransferResult Transfer(string url, CookieContainer cookieContainer)
		{
			TransferResult rlt = new TransferResult();
			try
			{
				url = ResolveUrl(url);
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
				if (cookieContainer != null)
				{
					request.CookieContainer = cookieContainer;
				}
				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
				rlt.Result = reader.ReadToEnd();
				rlt.ContentEncoding = reader.CurrentEncoding;
				rlt.ContentType = response.ContentType;
				rlt.Success = true;
			}
			catch (Exception ex)
			{
				Exceptions.LogOnly(ex);
				rlt.Success = false;
			}
			return rlt;
		}
开发者ID:mind0n,项目名称:hive,代码行数:29,代码来源:NetHelper.cs

示例3: GetPage

 public string GetPage(string posturl)
 {
     Stream instream = null;
     StreamReader sr = null;
     HttpWebResponse response = null;
     HttpWebRequest request = null;
     Encoding encoding = Encoding.UTF8;
     // 准备请求...
     try
     {
         // 设置参数
         request = WebRequest.Create(posturl) as HttpWebRequest;
         CookieContainer cookieContainer = new CookieContainer();
         request.CookieContainer = cookieContainer;
         request.AllowAutoRedirect = true;
         request.Method = "GET";
         request.ContentType = "application/x-www-form-urlencoded";
         //发送请求并获取相应回应数据
         response = request.GetResponse() as HttpWebResponse;
         //直到request.GetResponse()程序才开始向目标网页发送Post请求
         instream = response.GetResponseStream();
         sr = new StreamReader(instream, encoding);
         //返回结果网页(html)代码
         string content = sr.ReadToEnd();
         string err = string.Empty;
         Response.Write(content);
         return content;
     }
     catch (Exception ex)
     {
         string err = ex.Message;
         return string.Empty;
     }
 }
开发者ID:K-Library-NET,项目名称:PopcornStudios,代码行数:34,代码来源:SelectMenu.aspx.cs

示例4: Post

 public static HttpWebRequest Post(string url, CookieContainer cookies = null)
 {
     var request = CreateRequest(new Uri(url), cookies);
     request.Method = WebRequestMethods.Http.Post;
     request.ContentType = "application/x-www-form-urlencoded";
     return request;
 }
开发者ID:XcodeFi,项目名称:InstagramUser,代码行数:7,代码来源:HttpRequestBuilder.cs

示例5: GetLoginUrl

        public bool GetLoginUrl(string userId, string password, string dmtrackPageid, string st, ref CookieContainer cookieContainer)
        {
            string preUrl = "https://login.alibaba.com/validateST.htm?pd=alibaba&pageFrom=standardlogin&u_token=&xloginPassport={0}&xloginPassword={1}&xloginCheckToken=&rememberme=rememberme&runatm=runatm&dmtrack_pageid={2}&st={3}";
            string url = string.Format(preUrl, userId, password, dmtrackPageid, st);
            string html = HttpHelper.GetHtml(url);
            string xloginCallBackForRisUrl = "https://login.alibaba.com/xloginCallBackForRisk.do";
            string postString = "dmtrack_pageid_info=" + dmtrackPageid + "&xloginPassport=" + userId + "&xloginPassword=" + password + "&ua=&pd=alibaba";
            HttpHelper.GetHtml(xloginCallBackForRisUrl, postString, cookieContainer);

            if (string.IsNullOrEmpty(html) || html.IndexOf("var xman_success=") == -1)
            {
                return false;
            }
            string context = html.Replace("var xman_success=", "").Trim();
            AliLoginUser aliLoginUser = JsonConvert.FromJson<AliLoginUser>(context);
            List<string> urls = aliLoginUser.xlogin_urls;
            foreach (string urlstring in urls)
            {
                HttpHelper.GetHtml(urlstring, cookieContainer);
            }
            string manageHtml = HttpHelper.GetHtml(HttpClient.ManageHtml, cookieContainer);
            DataCache.Instance.CsrfToken = HttpClient.GetCsrfToken(manageHtml);
            DataCache.Instance.CheckCodeUrl = HttpClient.GetCheckCodeUrl(manageHtml);
            DataCache.Instance.AliID = FileUtils.GetAliId(cookieContainer, Constants.HomeUrl);
            ShareCookie.Instance.LoginCookieContainer = cookieContainer;
            return true;
        }
开发者ID:rew170,项目名称:soomecode,代码行数:27,代码来源:Passporter.cs

示例6: Build

 public IWebRequest Build(string url, IEnumerable<KeyValuePair<string, string>> headers, CookieContainer cookieContainer, bool allowAutoRedirect = true)
 {
     var request = WebRequest.Create(url);
     var httpRequest = request as HttpWebRequest;
     httpRequest.AllowAutoRedirect = allowAutoRedirect;
     httpRequest.CookieContainer = cookieContainer;
     foreach (var kvp in headers)
     {
         switch (kvp.Key.ToUpperInvariant())
         {
             case "HOST":
                 httpRequest.Host = kvp.Value;
                 break;
             case "REFERER":
                 httpRequest.Referer = kvp.Value;
                 break;
             case "USER-AGENT":
                 httpRequest.UserAgent = kvp.Value;
                 break;
             case "ACCEPT":
                 httpRequest.Accept = kvp.Value;
                 break;
             default:
                 httpRequest.Headers.Add(kvp.Key, kvp.Value);
                 break;
         }
     }
     return new DesktopWebRequest(httpRequest);
 }
开发者ID:CrshOverride,项目名称:CourseraDotNet,代码行数:29,代码来源:DesktopRequestBuilder.cs

示例7: PrimeDice

 public PrimeDice()
 {
     _CC = new CookieContainer();
     _CC.Add(new Cookie("user", "43579", "/", "primedice.com"));
     _CC.Add(new Cookie("password", "ea1a3c", "/", "primedice.com"));
     _CC.Add(new Cookie("betting", "1", "/", "primedice.com"));
 }
开发者ID:KBrizzle,项目名称:PrimeDiceBot,代码行数:7,代码来源:PrimeDice.cs

示例8: ConvertToCookieContainer

        /// <summary>
        /// convert cookies string to CookieContainer
        /// </summary>
        /// <param name="cookies"></param>
        /// <returns></returns>
        public static CookieContainer ConvertToCookieContainer(Dictionary<string, string> cookies)
        {
            CookieContainer cookieContainer = new CookieContainer();

            foreach (var cookie in cookies)
            {
                string[] strEachCookParts = cookie.Value.Split(';');
                int intEachCookPartsCount = strEachCookParts.Length;

                foreach (string strCNameAndCValue in strEachCookParts)
                {
                    if (!string.IsNullOrEmpty(strCNameAndCValue))
                    {
                        Cookie cookTemp = new Cookie();
                        int firstEqual = strCNameAndCValue.IndexOf("=");
                        string firstName = strCNameAndCValue.Substring(0, firstEqual);
                        string allValue = strCNameAndCValue.Substring(firstEqual + 1, strCNameAndCValue.Length - (firstEqual + 1));
                        cookTemp.Name = firstName;
                        cookTemp.Value = allValue;
                        cookTemp.Path = "/";
                        cookTemp.Domain = cookie.Key;
                        cookieContainer.Add(cookTemp);
                    }
                }
            }
            return cookieContainer;
        }
开发者ID:yonglehou,项目名称:ToolRepository,代码行数:32,代码来源:Http3Helper.cs

示例9: ChencSubmitDatas

 protected bool ChencSubmitDatas(CookieContainer cookieContainer, String postData)
 {
     var submitAction = new SubmitOrderAction();
     var translation = new HTML_Translation();
     submitAction.PostData = postData;
     var str = submitAction.CheckOrderInfoEx(cookieContainer);
     var returnString = translation.TranslationHtmlEx(str);
     if (returnString["data"]["errMsg"] != null && returnString["data"]["errMsg"].ToString() != "")
     {
         return  _checkState = false;
     }
     if (str.Contains("取消次数过多"))
     {
         return _checkState = false;
     }
     if (returnString["data"]["get608Msg"] != null)
     {
         return  _checkState = false;
     }
     if (returnString["messages"].Any())
     {
         return _checkState = false;
     }
     return _checkState = true;
 }
开发者ID:shepherds126,项目名称:12306_Helper,代码行数:25,代码来源:GetDatas_Background.cs

示例10: GetVideoUrl

 public override string GetVideoUrl(string url)
 {
     CookieContainer cc = new CookieContainer();
     string fullUrl = url + "?ss=1";
     string webData = WebCache.Instance.GetWebData(fullUrl, "ss=1&sss=1", cc);
     Match m = Regex.Match(webData, @"var\st=setTimeout\(""lc\('(?<s>[^']*)','(?<k>[^']*)','(?<t>[^']*)','(?<key>[^']*)'\)"",[^\)]*\);");
     if (m.Success)
     {
         string newUrl = String.Format(@"http://www.ecostream.tv/lo/mq.php?s={0}&k={1}&t={2}&key={3}",
             m.Groups["s"].Value, m.Groups["k"].Value, m.Groups["t"].Value, m.Groups["key"].Value);
         webData = WebCache.Instance.GetWebData(newUrl, "", cc, referer: fullUrl);
         m = Regex.Match(webData, @"<param\sname=""flashvars""\svalue=""file=(?<url>[^&]*)&[^>]*>");
         if (m.Success)
         {
             newUrl = HttpUtility.UrlDecode(m.Groups["url"].Value);
             if (!Uri.IsWellFormedUriString(newUrl, UriKind.Absolute))
             {
                 Uri uri = null;
                 if (Uri.TryCreate(new Uri(url), newUrl, out uri))
                 {
                     return WebCache.Instance.GetRedirectedUrl(uri.ToString() + "&start=0");
                 }
             }
         }
     }
     return String.Empty;
 }
开发者ID:leesanghyun2,项目名称:mp-onlinevideos2,代码行数:27,代码来源:EcoStream.cs

示例11: ExecuteHttpVerb

        private static WebResponse ExecuteHttpVerb(string url, string verbData, CookieContainer cookieContainer = null, string contentType = "application/x-www-form-urlencoded", string verb = "POST")
        {
            try
            {

                WebRequest request = WebRequest.Create(url);

                HttpWebRequest wr = request as HttpWebRequest;
                if (cookieContainer != null)
                    wr.CookieContainer = cookieContainer;
                wr.AllowAutoRedirect = false;
                request.Method = verb;
                wr.Proxy = null;
                wr.UserAgent = UserAgent;
                if (!string.IsNullOrEmpty(verbData))
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(verbData);
                    request.ContentType = contentType;
                    request.ContentLength = byteArray.Length;
                    Stream dataStream = request.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
                }
                WebResponse response = request.GetResponse();

                return response;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
开发者ID:BikS2013,项目名称:bUtility,代码行数:33,代码来源:WebClientHelper.cs

示例12: Meteor

 public Meteor()
 {
     cookies = new Cookie();
     cookies.Domain = "http://www.meteor.ie";
     cookies.Name = "meteor";
     cookieContainer = new CookieContainer();
 }
开发者ID:miconico,项目名称:AIB24Base,代码行数:7,代码来源:clsMeteor.cs

示例13: HttpGet

        /// <summary>
        /// 使用Get方法获取字符串结果(加入Cookie)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string HttpGet(string url, CookieContainer cookieContainer = null, Encoding encoding = null, int timeOut = App.AppRequestTimeOut)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Timeout = timeOut;

            if (cookieContainer != null)
            {
                request.CookieContainer = cookieContainer;
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (cookieContainer != null)
            {
                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
            }

            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
                {
                    string retString = myStreamReader.ReadToEnd();
                    return retString;
                }
            }
        }
开发者ID:fanpan26,项目名称:PzWxUtils,代码行数:34,代码来源:RequestUtility.cs

示例14: SavePostThread

 public SavePostThread(CookieContainer cookie, string userAgent, List<SavedListing> posts, bool save)
 {
     mCookie = cookie;
     mUserAgent = userAgent;
     postsToSave = posts;
     mSave = save;
 }
开发者ID:albertonoys,项目名称:RedditSaveTransfer,代码行数:7,代码来源:SavePostThread.cs

示例15: LoginNormal

        private void LoginNormal(string username,string password,string data,ref CookieContainer cookies)
        {
            //POST login data
            Dictionary<string,string> postData = new Dictionary<string, string> ();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create ("https://www.livecoding.tv/accounts/login/");
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
            request.CookieContainer = cookies;
            request.Method = "POST";
            request.Referer = "https://www.livecoding.tv/accounts/login/";
            request.ContentType = "application/x-www-form-urlencoded";

            postData.Add ("csrfmiddlewaretoken", HtmlHelper.getAttribute(HtmlHelper.getSingleElement(data,"<input type='hidden' name='csrfmiddlewaretoken'"),"value"));
            postData.Add ("login", username);
            postData.Add ("password", password);
            byte[] postBuild = HttpHelper.CreatePostData (postData);
            request.ContentLength = postBuild.Length;
            request.GetRequestStream ().Write (postBuild, 0, postBuild.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            using (System.IO.StreamReader sr = new System.IO.StreamReader (response.GetResponseStream ())) {
                data = sr.ReadToEnd();
            }

            if (LoginCompleted != null)
                LoginCompleted (this, cookies);
        }
开发者ID:CsharpLassi,项目名称:LiveCodingChat,代码行数:26,代码来源:EmailLogin.cs


注:本文中的System.Net.CookieContainer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。