• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# CookieContainer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: 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:proson,项目名称:wechat,代码行数:34,代码来源:selectMenu.aspx.cs


示例2: Capacity_Set_Invalid

        public static void Capacity_Set_Invalid()
        {
            CookieContainer cc = new CookieContainer();

            Assert.Throws<ArgumentOutOfRangeException>(() => cc.Capacity = 0); // <= 0
            Assert.Throws<ArgumentOutOfRangeException>(() => cc.Capacity = cc.PerDomainCapacity - 1); // < per domain capacity
        }
开发者ID:natemcmaster,项目名称:corefx,代码行数:7,代码来源:CookieContainerTest.cs


示例3: GetCookies_AddCookieVersion0WithExplicitDomain_CookieReturnedForDomainAndSubdomains

        public void GetCookies_AddCookieVersion0WithExplicitDomain_CookieReturnedForDomainAndSubdomains()
        {
            const string SchemePrefix = "http://";
            const string OriginalDomain = "contoso.com";

            var container = new CookieContainer();
            var cookie1 = new Cookie(CookieName1, CookieValue1) { Domain = OriginalDomain };
            container.Add(new Uri(SchemePrefix + OriginalDomain), cookie1);

            var uri = new Uri(SchemePrefix + OriginalDomain);
            var cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);
            Assert.Equal(OriginalDomain, cookies[CookieName1].Domain);

            uri = new Uri(SchemePrefix + "www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);

            uri = new Uri(SchemePrefix + "x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);

            uri = new Uri(SchemePrefix + "y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);

            uri = new Uri(SchemePrefix + "z.y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(1, cookies.Count);
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:30,代码来源:CookieContainerTest.cs


示例4: CreateCount11Container

        private static CookieContainer CreateCount11Container()
        {
            CookieContainer cc1 = new CookieContainer();
            // Add(Cookie)
            cc1.Add(c1);
            cc1.Add(c2);
            cc1.Add(c3);
            cc1.Add(c4);

            // Add(CookieCollection)
            CookieCollection cc2 = new CookieCollection();
            cc2.Add(c5);
            cc2.Add(c6);
            cc2.Add(c7);
            cc1.Add(cc2);

            // Add(Uri, Cookie)
            cc1.Add(u4, c8);
            cc1.Add(u4, c9);

            // Add(Uri, CookieCollection)
            cc2 = new CookieCollection();
            cc2.Add(c10);
            cc2.Add(c11);
            cc1.Add(u5, cc2);

            return cc1;
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:28,代码来源:CookieContainerTest.cs


示例5: GetCookies_AddCookiesWithImplicitDomain_CookiesReturnedOnlyForExactDomainMatch

        public void GetCookies_AddCookiesWithImplicitDomain_CookiesReturnedOnlyForExactDomainMatch()
        {
            const string SchemePrefix = "http://";
            const string OriginalDomain = "contoso.com";

            var container = new CookieContainer();
            var cookie1 = new Cookie(CookieName1, CookieValue1);
            var cookie2 = new Cookie(CookieName2, CookieValue2) { Version = 1 };
            var uri = new Uri(SchemePrefix + OriginalDomain);
            container.Add(uri, cookie1);
            container.Add(uri, cookie2);

            var cookies = container.GetCookies(uri);
            Assert.Equal(2, cookies.Count);
            Assert.Equal(OriginalDomain, cookies[CookieName1].Domain);
            Assert.Equal(OriginalDomain, cookies[CookieName2].Domain);

            uri = new Uri(SchemePrefix + "www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);

            uri = new Uri(SchemePrefix + "x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);

            uri = new Uri(SchemePrefix + "y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);

            uri = new Uri(SchemePrefix + "z.y.x.www." + OriginalDomain);
            cookies = container.GetCookies(uri);
            Assert.Equal(0, cookies.Count);
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:33,代码来源:CookieContainerTest.cs


示例6: CookiePortTest

 public CookiePortTest()
 {
     _cc = new CookieContainer();
     _cookie = new Cookie("name", "value1", "/path", "localhost");
     // use both space and comma as delimiter
     _cookie.Port = "\"80 110,1050, 1090 ,1100\"";
     _cc.Add(new Uri("http://localhost/path"), _cookie);
 }
开发者ID:ChuangYang,项目名称:corefx,代码行数:8,代码来源:CookiePortTest.cs


示例7: AddCookieCollection_Success

 public static void AddCookieCollection_Success()
 {
     CookieContainer cc = new CookieContainer();
     CookieCollection cookieCollection = new CookieCollection();
     cookieCollection.Add(new Cookie("name3", "value","/",".contoso.com"));
     cc.Add(cookieCollection);
     Assert.Equal(1, cc.Count);
 }
开发者ID:dotnet,项目名称:corefx,代码行数:8,代码来源:CookieContainerAddTest.cs


示例8: GetResponseByRequest

    public GetResponseByRequest(string url, string data, CookieContainer ccIn)
    {
        this.url = url;
        this.sendData = data;
        this.cc = ccIn;

        this.requestTimeout = 120000; //iki deqiqe;
    }
开发者ID:ElvinEfendi,项目名称:AutoCongratulator-Client-Program,代码行数:8,代码来源:GetResponseByRequest.cs


示例9: MaxCookieSize_GetSet_Success

        public static void MaxCookieSize_GetSet_Success()
        {
            CookieContainer cc = new CookieContainer();
            Assert.Equal(CookieContainer.DefaultCookieLengthLimit, cc.MaxCookieSize);

            cc.MaxCookieSize = 8192;
            Assert.Equal(8192, cc.MaxCookieSize);
        }
开发者ID:natemcmaster,项目名称:corefx,代码行数:8,代码来源:CookieContainerTest.cs


示例10: Ctor_CapacityPerDomainCapacityMaxCookieSize_Success

        public static void Ctor_CapacityPerDomainCapacityMaxCookieSize_Success()
        {
            CookieContainer cc = new CookieContainer(5, 4, 3);
            Assert.Equal(5, cc.Capacity);
            Assert.Equal(4, cc.PerDomainCapacity);
            Assert.Equal(3, cc.MaxCookieSize);

            cc = new CookieContainer(10, int.MaxValue, 4); // Even though PerDomainCapacity > Capacity, this shouldn't throw
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:9,代码来源:CookieContainerTest.cs


示例11: EndSession

	static void EndSession (CookieContainer container)
	{
		HttpWebRequest request = (HttpWebRequest) WebRequest.Create ("http://localhost:8081/end.aspx");
		request.CookieContainer = container;
		request.Method = "GET";

		HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
		response.Close ();
	}
开发者ID:mono,项目名称:gert,代码行数:9,代码来源:test.cs


示例12: Add_CookieVersion1AndRootDomainWithNoLeadingDot_ThrowsCookieException

        public void Add_CookieVersion1AndRootDomainWithNoLeadingDot_ThrowsCookieException()
        {
            const string SchemePrefix = "http://";
            const string OriginalDomain = "contoso.com";

            var container = new CookieContainer();
            var cookie = new Cookie(CookieName1, CookieValue1) { Version = 1, Domain = OriginalDomain };
            var uri = new Uri(SchemePrefix + OriginalDomain);
            Assert.Throws<CookieException>(() => container.Add(uri, cookie));
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:10,代码来源:CookieContainerTest.cs


示例13: RequisicaoRV

    public DataPrev.Domain.SistemaModel.ErroModel RequisicaoRV(long NumeroBeneficio)
    {
        DataPrev.Domain.SistemaModel.ErroModel Retorno = new Domain.SistemaModel.ErroModel();
        try
        {

            Domain.SistemaModel.IpModel IpList = new Domain.SistemaModel.IpModel();
            if (System.Configuration.ConfigurationManager.AppSettings["Consulta"] == "Lote")
                IpList = Rep.IpsLiberados();
            if (System.Configuration.ConfigurationManager.AppSettings["Consulta"] == "Sistema")
                IpList = Rep.IpsLiberados2();
            WebProxy proxyObj = new WebProxy(IpList.IP, IpList.Porta);
            proxyObj.Credentials = CredentialCache.DefaultCredentials;
            Retorno.Retorno3 = IpList.IP;

            Uri link = new Uri("http://www010.dataprev.gov.br/CWS/BIN/CWS.asp");
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(link);
            request.ProtocolVersion = HttpVersion.Version10;
            request.Proxy = proxyObj;
            request.Credentials = CredentialCache.DefaultCredentials;

            CookieContainer _Cookies = new CookieContainer();
            request.CookieContainer = _Cookies;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Referer = "http://www3.dataprev.gov.br/cws/contexto/hiscre/hiscrenet2.asp";

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] byteArray = Encoding.UTF8.GetBytes("C_1=BLR00.11&C_2=&C_3=" + NumeroBeneficio + "&layout=8%2C69%2C10%2C8%2C1&submit=Transmite");
            request.ContentLength = byteArray.Length;

            var h = request.CookieContainer.GetCookies(request.RequestUri);
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            int d = dataStream.ReadTimeout;
            dataStream.Close();

            //Fonte extrato retorno
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            Retorno.Fonte = reader.ReadToEnd();

            response.Close();
            request.Abort();
        }
        catch (Exception e)
        {
            Retorno.Fonte = e.Message;
        }
        Thread.Sleep(20000);

        return Retorno;
    }
开发者ID:Perobense,项目名称:PizzaIFSP,代码行数:54,代码来源:ServiceConsultaCep.cs


示例14: Capacity_GetSet_Success

        public static void Capacity_GetSet_Success()
        {
            CookieContainer cc = new CookieContainer();
            Assert.Equal(CookieContainer.DefaultCookieLimit, cc.Capacity);

            cc.Capacity = 900;
            Assert.Equal(900, cc.Capacity);

            cc.Capacity = 40; //Shrink
            Assert.Equal(40, cc.Capacity);
        }
开发者ID:natemcmaster,项目名称:corefx,代码行数:11,代码来源:CookieContainerTest.cs


示例15: Main

	static int Main ()
	{
		CookieContainer cookies = new CookieContainer ();

		HttpWebRequest request = (HttpWebRequest) WebRequest.Create ("http://localhost:8081/Default.aspx");
		request.CookieContainer = cookies;
		request.Method = "GET";

		try {
			HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
			using (StreamReader sr = new StreamReader (response.GetResponseStream (), Encoding.UTF8, true)) {
				string result = sr.ReadToEnd ();

				Assert.IsTrue (result.IndexOf ("<p>1</p>") != -1, "#A:" + result);
			}
			response.Close ();
		} catch (WebException ex) {
			HttpWebResponse response = (HttpWebResponse) ex.Response;
			if (response != null) {
				using (StreamReader sr = new StreamReader (response.GetResponseStream ())) {
					Console.WriteLine (sr.ReadToEnd ());
				}
			}
			return 1;
		}

		request = (HttpWebRequest) WebRequest.Create ("http://localhost:8081/Default.aspx");
		request.CookieContainer = cookies;
		request.Method = "GET";

		try {
			HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
			using (StreamReader sr = new StreamReader (response.GetResponseStream (), Encoding.UTF8, true)) {
				string result = sr.ReadToEnd ();

				Assert.IsTrue (result.IndexOf ("<p>2</p>") != -1, "#B:" + result);
			}
			response.Close ();
		} catch (WebException ex) {
			HttpWebResponse response = (HttpWebResponse) ex.Response;
			if (response != null) {
				using (StreamReader sr = new StreamReader (response.GetResponseStream ())) {
					Console.WriteLine (sr.ReadToEnd ());
				}
			}
			return 2;
		}

		return 0;
	}
开发者ID:mono,项目名称:gert,代码行数:50,代码来源:test.cs


示例16: GetCookieHeader

        public static string GetCookieHeader(Uri uri, CookieContainer cookies)
        {
            string cookieHeader = null;

            Debug.Assert(cookies != null);

            string cookieValues = cookies.GetCookieHeader(uri);
            if (!string.IsNullOrEmpty(cookieValues))
            {
                cookieHeader = CookieHeaderNameWithColon + " " + cookieValues;                
            }

            return cookieHeader;
        }        
开发者ID:er0dr1guez,项目名称:corefx,代码行数:14,代码来源:WinHttpCookieContainerAdapter.cs


示例17: RequestGet

 public static void RequestGet(string url, HandleResponse callback, CookieContainer cookies, params string[] post_data_pair)
 {
     if (post_data_pair != null && post_data_pair.Length%2!=0)
     {
         Debug.LogError("Post data params shoud be an array of name and value pairs");
         return;
     }
     // create get data
     string post_data = "";
     for (int i = 0; i < post_data_pair.Length; i+=2)
         post_data += post_data_pair[i]+"="+post_data_pair[i+1]+((i==post_data_pair.Length-2)? "":"&");
     if (post_data != "") url += "?"+post_data;
     // create request
     HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
     req.Method = "GET";
     req.ContentType = "application/x-www-form-urlencoded";
     req.AllowWriteStreamBuffering = true;
     req.KeepAlive = true;
     req.Timeout = 4000;
     // append cookies
     if (cookies == null)
         req.CookieContainer = new CookieContainer();
     else
     {
         req.CookieContainer = cookies;
     }
     // get response
     HttpWebResponse response = (HttpWebResponse)req.GetResponse();
     Stream streamResponse = response.GetResponseStream();
     StreamReader streamRead = new StreamReader(streamResponse);
     string responseString = streamRead.ReadToEnd();
     if (callback != null) callback(responseString, req.CookieContainer);
     streamResponse.Close();
     streamRead.Close();
     /*
     req.BeginGetResponse(
     delegate(System.IAsyncResult asynchronousResult)
     {
         HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         Stream streamResponse = response.GetResponseStream();
         StreamReader streamRead = new StreamReader(streamResponse);
         string responseString = streamRead.ReadToEnd();
         if (callback != null) callback(responseString, request.CookieContainer);
         streamResponse.Close();
         streamRead.Close();
         response.Close();
     }, req);*/
 }
开发者ID:peyman-abdi,项目名称:unity_agents,代码行数:49,代码来源:WebAgent.cs


示例18: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        // first, request the login form to get the viewstate value
        HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
        StreamReader responseReader = new StreamReader(
              webRequest.GetResponse().GetResponseStream()
           );
        string responseData = responseReader.ReadToEnd();
        responseReader.Close();
        System.Threading.Thread.Sleep(3000);
        // extract the viewstate value and build out POST data
        string viewState = ExtractViewState(responseData);
        string eventValidation = ExtractEventValidation(responseData);
        string postData =
              String.Format(
                 "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE={0}&__EVENTVALIDATION={1}&LogOn1$UserName={2}&LogOn1$Password={3}&LogOn1$LoginButton=Log In",
                 viewState,eventValidation, "CLT", "TEST"
              );

        // have a cookie container ready to receive the forms auth cookie
        CookieContainer cookies = new CookieContainer();
        // now post to the login form
        webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.CookieContainer = cookies;
        webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
        webRequest.KeepAlive = false;
        webRequest.Referer = LOGIN_URL;
        webRequest.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        webRequest.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
        webRequest.Headers.Add("Accept-Language", "en-US,en;q=0.8");
        // write the form values into the request message;
        StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
        requestWriter.Write(postData);
        requestWriter.Close();
        // we don't need the contents of the response, just the cookie it issues
        webRequest.GetResponse().Close();

        // now we can send out cookie along with a request for the protected page
        webRequest = WebRequest.Create("https://clients.rentrecoverysolutions.com/Home.aspx") as HttpWebRequest;
        webRequest.CookieContainer = cookies;
        responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
        // and read the response
        responseData = responseReader.ReadToEnd();
        responseReader.Close();

        Response.Write(responseData);
    }
开发者ID:KPratap,项目名称:PropSolutions,代码行数:49,代码来源:Test2.aspx.cs


示例19: PerDomainCapacity_GetSet

        public static void PerDomainCapacity_GetSet()
        {
            CookieContainer cc = new CookieContainer();
            Assert.Equal(CookieContainer.DefaultPerDomainCookieLimit, cc.PerDomainCapacity);

            cc.PerDomainCapacity = 50;
            Assert.Equal(50, cc.PerDomainCapacity);

            cc.PerDomainCapacity = 40; // Shrink
            Assert.Equal(40, cc.PerDomainCapacity);

            // Shrink to one - this should get rid of all cookies since there are no possible cookies that can be expired
            cc.PerDomainCapacity = 1;
            Assert.Equal(1, cc.PerDomainCapacity);
            Assert.Equal(0, cc.Count);
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:16,代码来源:CookieContainerTest.cs


示例20: yt

    public static SortedDictionary<int, string> yt(string targetUri)
    {
        CookieContainer cc = new CookieContainer();
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(targetUri);
        req.CookieContainer = cc;
        req.Timeout = 5000;
        req.GetResponse().Close();
        req = (HttpWebRequest)WebRequest.Create("http://www.youtube.com/get_video_info?video_id=" + Regex.Match(targetUri, "(?<=v=)[\\w-]+").Value);
        req.CookieContainer = cc;
        string _info = null;
        System.Net.WebResponse res = req.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream());
        _info = sr.ReadToEnd();
        sr.Close();
        res.Close();
        Hashtable info = new Hashtable();
        Dictionary<string, string> _tmp = new Dictionary<string, string>();
        SortedDictionary<int, string> fmtmap = new SortedDictionary<int, string>();

        foreach (string item in _info.Split('&'))
        {
            info.Add(item.Split('=')[0], Uri.UnescapeDataString(item.Split('=')[1]));
        }
        if (Convert.ToString(info["status"]) == "fail")
        {
            throw new UnauthorizedAccessException();
        }
        foreach (string item in Convert.ToString(info["url_encoded_fmt_stream_map"]).Split(','))
        {
            foreach (string a in item.Split('&'))
            {
                _tmp.Add(a.Split('=')[0], Uri.UnescapeDataString(a.Split('=')[1]));
            }
            fmtmap.Add(Convert.ToInt32(_tmp["itag"]), (_tmp["url"]) + "&signature=");
            _tmp.Clear();
        }

        req = (HttpWebRequest)WebRequest.Create("http://www.youtube.com/get_video_info?video_id=" + Regex.Match(targetUri, "(?<=v=)\\w+").Value + "&t=" + Convert.ToString(info["token"]));
        req.CookieContainer = cc;
        req.Timeout = 1500;
        req.GetResponse().Close();

        fmtmap[-2] = Convert.ToString(info["title"]);
        fmtmap[-1] = cc.GetCookieHeader(new Uri("http://www.youtube.com"));
        info.Clear();
        return fmtmap;
    }
开发者ID:kazuki0824,项目名称:Breeze-Mono,代码行数:47,代码来源:kk_movdl_csharp.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Coord类代码示例发布时间:2022-05-24
下一篇:
C# Cookie类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap