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


C# CookieContainer.GetCookieHeader方法代码示例

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


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

示例1: FindSessionId

        public TrackemonSession FindSessionId()
        {
            var trackemonSession = new TrackemonSession();
            try
            {
                var cookieContainer = new CookieContainer();
                const string homepageUrl = "https://www.trackemon.com";
                var request = WebRequest.CreateHttp(homepageUrl);
                request.Method = "GET";
                request.Timeout = Timeout;
                request.CookieContainer = cookieContainer;
                using (var response = request.GetResponse())
                {
                    var cookieHeader = cookieContainer.GetCookieHeader(new Uri("https://www.trackemon.com"));
                    trackemonSession.cookieHeader = cookieHeader;
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        string line;

                        while ((line = reader.ReadLine()) != null)
                        {
                            var match = Regex.Match(line, @"var\s+sessionId\s*=\s*\'(1?.*)\'\s*;");
                            if (match.Success)
                            {
                                trackemonSession.sessionId = match.Groups[1].Value;
                                return trackemonSession;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Debug("Error trying to get a sessionId for Trackemon: {0}", e.Message);
            }
            return null;
        }
开发者ID:ChronoXNL,项目名称:PogoLocationFeeder,代码行数:37,代码来源:TrackermonRarePokemonRepository.cs

示例2: createWebClient

        public static MyWebClient createWebClient(CookieContainer ccntr=null, string referer=null)
        {
            MyWebClient wbclnt = new MyWebClient();

            // Header 字段可以在发出请求报文后丢失,因此必须重新设置
            wbclnt.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
            wbclnt.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            wbclnt.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            wbclnt.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
            wbclnt.Headers.Add(HttpRequestHeader.Referer, referer);
            wbclnt.Encoding = new UTF8Encoding();

            if (ccntr != null)
            {
                /// wbclnt.Headers.Add(HttpRequestHeader.Cookie, cookie);
                wbclnt.CookieContainer = ccntr;
                _cookie = ccntr.GetCookieHeader(new Uri(referer));
                LogHelper.info("create webclient with cookie : " + _cookie);
            }

            if (referer != null) _referer = referer;

            return wbclnt;
        }
开发者ID:cowmax,项目名称:MyProjects,代码行数:24,代码来源:ThreadMgr.cs

示例3: Execute

        /// <summary>
        /// Request a resource from Reddit
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        internal HttpStatusCode Execute(out string json)
        {
            // Default empty Json
            json = "[]";
            string Data = json;
            HttpStatusCode Status = HttpStatusCode.Unused;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            if (Proxy != null)
                request.Proxy = Proxy;

            request.ServicePoint.ConnectionLimit = 100;
            request.Timeout = RequestTimeout;
            request.Method = Method;
            request.UserAgent = UserAgent;
            if (!String.IsNullOrEmpty(Cookie))
            {
                CookieContainer redditCookie = new CookieContainer();
                Uri cookieuri = new Uri(Url + User);
                redditCookie.Add(cookieuri, new Cookie("reddit_session", Cookie.Replace(",", "%2c").Replace(":", "%3A"), "/", "reddit.com"));
                request.Headers["cookie"] = redditCookie.GetCookieHeader(cookieuri);
            }

            using (var handle = new ManualResetEvent(false))
            {
                if (!string.IsNullOrEmpty(Content))
                {
                    // set the content type of the posted data
                    request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

                    // Write the XML data to the post form, as part of the 'xml' variable
                    request.BeginGetRequestStream(ar =>
                    {
                        try
                        {
                            using (var requestStream = request.EndGetRequestStream(ar))
                            using (var writeStream = new StreamWriter(requestStream, Encoding.ASCII))
                            {
                                writeStream.Write(Content);
                            }
                        }
                        catch (Exception exp)
                        {
                            Debug.WriteLine("Request.Execute: " + exp.Message);
                            Console.WriteLine("Request.Execute: " + exp.Message);
                            throw exp;
                        }
                        finally
                        {
                            handle.Set();
                        }

                    }, new object() /* state */);
                    handle.WaitOne();
                    handle.Reset();
                }

                request.BeginGetResponse(ar =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(ar);

                        using (var receiveStream = response.GetResponseStream())
                        using (var readStream = new StreamReader(receiveStream, Encoding.ASCII))
                        {
                            Data = readStream.ReadToEnd();
                        }

                        Status = response.StatusCode;

                        // Update the cache hash & the time the URL was requested
                        // if the request was successful, that way we don't count
                        // failed requests in the 30 second limit
                        // throw new NotImplementedException();

                    }
                    catch (Exception exp)
                    {
                        Debug.WriteLine("Request.Execute: " + exp.Message);
                        Console.WriteLine("Request.Execute: " + exp.Message);
                    }
                    finally
                    {
                        handle.Set();
                    }

                }, new object() /* state */);

                // In case the first timeout doesn't work then move onto then
                // we'll let the wait request handle timeout as well
                handle.WaitOne(RequestTimeout + (RequestTimeout / 10));
            }
            json = Data;
//.........这里部分代码省略.........
开发者ID:Kalfira,项目名称:SquaresAndRectangles,代码行数:101,代码来源:Request.cs

示例4: GetCookieHeader

        // TODO: Refactor to smaller files. Perhaps split cookie handling into separate class.
        private static string GetCookieHeader(Uri uri, CookieContainer cookies)
        {
            string cookieHeader = null;

            Debug.Assert(cookies != null);

            string cookieValues = cookies.GetCookieHeader(uri);
            if (!string.IsNullOrEmpty(cookieValues))
            {
                cookieHeader = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", HeaderNameCookie, cookieValues);
            }

            return cookieHeader;
        }
开发者ID:JerryForNet,项目名称:corefx,代码行数:15,代码来源:WinHttpHandler.cs

示例5: Login

        /// <summary>
        /// Logs the user in
        /// </summary>
        /// <param name="user">Reddit account username</param>
        /// <param name="pswd">Reddit account password</param>
        /// <returns>True/False depending on success of login</returns>
        public bool Login(string user, string pswd)
        {
            string postData = string.Format("api_type=json&user={0}&passwd={1}", user, pswd);
            string loginURI = m_domain + string.Format(APIPaths.login, user);
            Hashtable response = SendPOST(postData, loginURI);
            m_usr = user;

            m_errors = GetErrorsFromRedditJson(response);
            //First check for errors. Should always contain errors key.
            if (m_errors != "" )
            {
                return false;
            }
            //Only need the data segment
            Hashtable data = ((Hashtable)((Hashtable)response["json"])["data"]);
            m_modhash = data["modhash"].ToString();
            string cookieval = data["cookie"].ToString();

            redditCookie = new CookieContainer();
            Uri cookieuri = new Uri(m_domain + string.Format(APIPaths.login, user));
            redditCookie.Add(cookieuri, new Cookie("reddit_session", cookieval.Replace(",", "%2c").Replace(":", "%3A"), "/", "reddit.com"));
            jsonGet.Headers["cookie"] = redditCookie.GetCookieHeader(cookieuri);
            jsonGet.Headers["Useragent"] = m_useragent;
            m_logged_in = true;
            return true;
        }
开发者ID:ChrisWay,项目名称:Reddit-C--API,代码行数:32,代码来源:Reddit.cs

示例6: GetAllCookies_FireFox

        //Adapted from http://www.codeproject.com/Articles/330142/Cookie-Quest-A-Quest-to-Read-Cookies-from-Four-Pop
        private static string GetAllCookies_FireFox(string strHost)
        {
            string strPath, strTemp, strDb;
            strTemp = string.Empty;

            // Check to see if FireFox Installed
            strPath = GetFireFoxCookiePath();
            if (string.Empty == strPath) // Nope, perhaps another browser
                return null;

            try
            {
                // First copy the cookie jar so that we can read the cookies 
                // from unlocked copy while
                // FireFox is running
                strTemp = strPath + ".temp";
                strDb = "Data Source=" + strTemp + ";pooling=false";

                File.Copy(strPath, strTemp, true);

                // Now open the temporary cookie jar and extract Value from the cookie if
                // we find it.
                using (SQLiteConnection conn = new SQLiteConnection(strDb))
                {
                    using (SQLiteCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "SELECT name, value FROM moz_cookies WHERE host LIKE '%" +
                            strHost + "%';";

                        conn.Open();
                        CookieContainer cookies = new CookieContainer();
                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                cookies.Add(new Cookie(reader.GetString(0), reader.GetString(1), "/", StravaDomain));
                            }
                        }
                        return cookies.GetCookieHeader(new Uri("https://" + StravaDomain));
                    }
                }
            }
            finally
            {
                // All done clean up
                if (string.Empty != strTemp)
                {
                    File.Delete(strTemp);
                }
            }
        }
开发者ID:joker99,项目名称:GpxFromStrava,代码行数:52,代码来源:Form1.cs

示例7: GetResponse

        public HttpResponse GetResponse(HttpRequest request, CookieContainer cookies)
        {
            if (!CheckAvailability())
            {
                throw new ApplicationException("Curl failed to initialize.");
            }

            if (request.NetworkCredential != null)
            {
                throw new NotImplementedException("Credentials not supported for curl dispatcher.");
            }

            lock (CurlGlobalHandle.Instance)
            {
                Stream responseStream = new MemoryStream();
                Stream headerStream = new MemoryStream();

                using (var curlEasy = new CurlEasy())
                {
                    curlEasy.AutoReferer = false;
                    curlEasy.WriteFunction = (b, s, n, o) =>
                    {
                        responseStream.Write(b, 0, s * n);
                        return s * n;
                    };
                    curlEasy.HeaderFunction = (b, s, n, o) =>
                    {
                        headerStream.Write(b, 0, s * n);
                        return s * n;
                    };

                    curlEasy.Url = request.Url.AbsoluteUri;
                    switch (request.Method)
                    {
                        case HttpMethod.GET:
                            curlEasy.HttpGet = true;
                            break;

                        case HttpMethod.POST:
                            curlEasy.Post = true;
                            break;

                        case HttpMethod.PUT:
                            curlEasy.Put = true;
                            break;

                        default:
                            throw new NotSupportedException(string.Format("HttpCurl method {0} not supported", request.Method));
                    }
                    curlEasy.UserAgent = UserAgentBuilder.UserAgent;
                    curlEasy.FollowLocation = request.AllowAutoRedirect;

                    if (OsInfo.IsWindows)
                    {
                        curlEasy.CaInfo = "curl-ca-bundle.crt";
                    }

                    if (cookies != null)
                    {
                        curlEasy.Cookie = cookies.GetCookieHeader(request.Url);
                    }

                    if (!request.Body.IsNullOrWhiteSpace())
                    {
                        // TODO: This might not go well with encoding.
                        curlEasy.PostFieldSize = request.Body.Length;
                        curlEasy.SetOpt(CurlOption.CopyPostFields, request.Body);
                    }

                    // Yes, we have to keep a ref to the object to prevent corrupting the unmanaged state
                    using (var httpRequestHeaders = SerializeHeaders(request))
                    {
                        curlEasy.HttpHeader = httpRequestHeaders;

                        var result = curlEasy.Perform();

                        if (result != CurlCode.Ok)
                        {
                            throw new WebException(string.Format("Curl Error {0} for Url {1}", result, curlEasy.Url));
                        }
                    }

                    var webHeaderCollection = ProcessHeaderStream(request, cookies, headerStream);
                    var responseData = ProcessResponseStream(request, responseStream, webHeaderCollection);

                    var httpHeader = new HttpHeader(webHeaderCollection);

                    return new HttpResponse(request, httpHeader, responseData, (HttpStatusCode)curlEasy.ResponseCode);
                }
            }
        }
开发者ID:harsla,项目名称:Sonarr,代码行数:91,代码来源:CurlHttpDispatcher.cs

示例8: Main

 public static void Main(string[] args)
 {
     Uri uri = new Uri("http://myemsl-dev5.emsl.pnl.gov/");
     CookieContainer cc = new CookieContainer();
     Authenticate a = new Authenticate();
     int res;
     Console.WriteLine("T1a");
     res = a.process(cc);
     if(res == 0)
     {
         Console.WriteLine("Cookies {0}", cc.GetCookieHeader(uri));
         Console.WriteLine("Cookie Count {0} {1}", cc.GetCookies(uri).Count, cc.Capacity);
         foreach(Cookie cookie in cc.GetCookies(uri))
         {
             Console.WriteLine("Cookie {0}", cookie);
         }
         test_auth(new Uri("http://myemsl-dev5.emsl.pnl.gov/myemsl/testauth/"), cc);
         logout(new Uri("http://myemsl-dev5.emsl.pnl.gov/myemsl/logout/"), cc);
     }
     Console.WriteLine("T2");
     Console.WriteLine(res);
 }
开发者ID:EMSL-MSC,项目名称:pacifica-auth,代码行数:22,代码来源:test.cs

示例9: GetCookieHeader1

		public void GetCookieHeader1 ()
		{
			CookieContainer cc;
			Cookie cookie;

			cc = new CookieContainer ();
			cookie = new Cookie ("name1", "value1", "/path", "localhost");
			cookie.Comment = "Short name";
			cookie.Expires = DateTime.Now.Add (new TimeSpan (3, 2, 5));
			cookie.Version = 0;
			cc.Add (cookie);
			cookie = new Cookie ("name2", "value2", "/path/sub", "localhost");
			cookie.Comment = "Description";
			cookie.Expires = DateTime.Now.Add (new TimeSpan (3, 2, 5));
			cookie.Version = 1;
			cc.Add (cookie);
			Assert.AreEqual ("$Version=1; name2=value2; $Path=/path/sub; name1=value1", cc.GetCookieHeader (new Uri ("http://localhost/path/sub")), "#A1");
			Assert.AreEqual ("name1=value1", cc.GetCookieHeader (new Uri ("http://localhost/path")), "#A2");
			Assert.AreEqual (string.Empty, cc.GetCookieHeader (new Uri ("http://localhost/whatever")), "#A3");
		}
开发者ID:nestalk,项目名称:mono,代码行数:20,代码来源:CookieContainerTest.cs

示例10: CallHandlerInternal

        object CallHandlerInternal(string url, object data, HttpCookieCollection cookies)
        {
            Uri uri = new Uri(url);

            string postData;

            if (data != null)
                postData = "data=" + SessionHandler.GetSerializedString(data);
            else
                postData = "";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);

            try
            {
                // TODO: do we need to do better cookie handling?
                CookieContainer cookieContainer = new CookieContainer();

                if (cookies != null)
                {
                    foreach (string name in cookies.AllKeys)
                    {
                        string quotedCookieValue = cookies[name].Value;

                        if (quotedCookieValue == null)
                            quotedCookieValue = "";
                        else if (quotedCookieValue.IndexOfAny(new char[] { ',', ';' }) != -1)
                            quotedCookieValue = "\"" + quotedCookieValue.Replace("\"", "\\\"") + "\"";

                        try
                        {
                            cookieContainer.Add(new Cookie(name, quotedCookieValue, "/", uri.Host));
                        }
                        catch (Exception ex)
                        {
                            // Eat it -- we mainly want the session cookies anyway
                            // TODO: log
                        }
                    }
                }

                string cookieHeader = cookieContainer.GetCookieHeader(uri);

                if (!string.IsNullOrEmpty(cookieHeader))
                    req.Headers["Cookie"] = cookieHeader;

                req.Method = "POST";
                req.ContentLength = postData.Length;
                req.ContentType = "application/x-www-form-urlencoded";

                // TODO: make this configurable
                // TODO: add better errors
                // TODO: use the polltimeout value on the control
                req.Timeout = 10000;
                req.ServicePoint.ConnectionLimit = 200;
                // TODO: pass through windows auth

                using (Stream s = req.GetRequestStream())
                using (StreamWriter w = new StreamWriter(s))
                {
                    w.Write(postData);
                }

                WebResponse resp = req.GetResponse();

                string responseData;

                using (Stream s = resp.GetResponseStream())
                using (StreamReader r = new StreamReader(s))
                {
                    responseData = r.ReadToEnd();
                }

                if (!string.IsNullOrEmpty(responseData))
                {
                    return SessionHandler.GetStringDeserialized(responseData);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
开发者ID:ideayapai,项目名称:docviewer,代码行数:87,代码来源:SessionStateSessionStorageProvider.cs

示例11: ToFilterString

        /// <summary>
        /// Gets a string that can be given to the MediaPortal Url Source Splitter holding the url and all parameters.
        /// </summary>
        internal override string ToFilterString()
        {
            ParameterCollection parameters = new ParameterCollection();

            if (this.IgnoreContentLength != HttpUrl.DefaultHttpIgnoreContentLength)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpIgnoreContentLength, this.IgnoreContentLength ? "1" : "0"));
            }
            if (this.OpenConnectionTimeout != HttpUrl.DefaultHttpOpenConnectionTimeout)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpOpenConnectionTimeout, this.OpenConnectionTimeout.ToString()));
            }
            if (this.OpenConnectionSleepTime != HttpUrl.DefaultHttpOpenConnectionSleepTime)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpOpenConnectionSleepTime, this.OpenConnectionSleepTime.ToString()));
            }
            if (this.TotalReopenConnectionTimeout != HttpUrl.DefaultHttpTotalReopenConnectionTimeout)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpTotalReopenConnectionTimeout, this.TotalReopenConnectionTimeout.ToString()));
            }
            if (String.CompareOrdinal(this.Referer, HttpUrl.DefaultHttpReferer) != 0)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpReferer, this.Referer.ToString()));
            }
            if (String.CompareOrdinal(this.UserAgent, HttpUrl.DefaultHttpUserAgent) != 0)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpUserAgent, this.UserAgent.ToString()));
            }

            if (this.Version == HttpVersion.Version10)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpVersion, HttpUrl.HttpVersionForce10.ToString()));
            }
            else if (this.Version == HttpVersion.Version11)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpVersion, HttpUrl.HttpVersionForce11.ToString()));
            }

            if (this.Cookies.Count > 0)
            {
                CookieContainer container = new CookieContainer(this.Cookies.Count);
                foreach (Cookie cookie in this.Cookies)
                {
                    container.Add(this.Uri, cookie);
                }
                parameters.Add(new Parameter(HttpUrl.ParameterHttpCookie, container.GetCookieHeader(this.Uri)));
            }

            if (this.CustomHeaders.Count > 0)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpHeadersCount, this.CustomHeaders.Count.ToString()));

                for (int i = 0; i < this.CustomHeaders.Count; i++)
                {
                    HttpHeader header = this.CustomHeaders[i];

                    parameters.Add(new Parameter(String.Format(HttpUrl.ParameterHttpHeaderFormatName, i), header.Name));
                    parameters.Add(new Parameter(String.Format(HttpUrl.ParameterHttpHeaderFormatValue, i), header.Value));
                    
                }
            }

            if (this.ServerAuthenticate)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpServerAuthenticate, "1"));
                parameters.Add(new Parameter(HttpUrl.ParameterHttpServerUserName, this.ServerUserName));
                parameters.Add(new Parameter(HttpUrl.ParameterHttpServerPassword, this.ServerPassword));
            }

            if (this.ProxyServerAuthenticate)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpProxyServerAuthenticate, "1"));
                parameters.Add(new Parameter(HttpUrl.ParameterHttpProxyServer, this.ProxyServer));
                parameters.Add(new Parameter(HttpUrl.ParameterHttpProxyServerPort, this.ProxyServerPort.ToString()));
                parameters.Add(new Parameter(HttpUrl.ParameterHttpProxyServerUserName, this.ProxyServerUserName));
                parameters.Add(new Parameter(HttpUrl.ParameterHttpProxyServerPassword, this.ProxyServerPassword));
                parameters.Add(new Parameter(HttpUrl.ParameterHttpProxyServerType, ((int)this.ProxyServerType).ToString()));
            }

            if (String.CompareOrdinal(this.StreamFileName, HttpUrl.DefaultStreamFileName) != 0)
            {
                parameters.Add(new Parameter(HttpUrl.ParameterHttpStreamFileName, this.StreamFileName.ToString()));
            }

            // return formatted connection string
            return base.ToFilterString() + ParameterCollection.ParameterSeparator + parameters.FilterParameters;
        }
开发者ID:offbyoneBB,项目名称:mp-onlinevideos2,代码行数:90,代码来源:HttpUrl.cs

示例12: Manager


//.........这里部分代码省略.........
                    diag.CancelMessage = "Trying to stop....";
                    diag.ShowDialog();

                    diag.Value = 1337; //will create desired marquee effect

                    string resp = "";

                    HttpWebResponse web = null;
                    var parameters = new StringBuilder();
                    foreach (string key in nvc)
                    {
                        parameters.AppendFormat("{0}={1}&",
                            HttpUtility.UrlEncode(key),
                            HttpUtility.UrlEncode(nvc[key]));
                    }
                    parameters.Length -= 1;

                    wc.Method = "POST";
                    wc.ContentType = "application/x-www-form-urlencoded";
                    wc.AllowAutoRedirect = false;

                    using (var writer = new StreamWriter(wc.GetRequestStream()))
                    {
                        writer.Write(parameters.ToString());
                    }

                    try
                    {
                        List<byte> buffer = new List<byte>();
                        web = (HttpWebResponse)wc.GetResponse();
                        Stream req = web.GetResponseStream();
                        while (true)
                        {
                            int bt = req.ReadByte();
                            if (bt == -1) break;
                            buffer.Add((byte)bt);
                        }
                        resp = Encoding.Default.GetString(buffer.ToArray());
                    }
                    catch (Exception z) { Out.WriteError(z.ToString()); resp = ""; }

                            CookieContainer cc = new CookieContainer();
                            string gh = web.Headers["Set-Cookie"];
                            cc.SetCookies(new Uri("http://imgur.com"), web.Headers["Set-Cookie"]);

                    bool loc = true;
                    try
                    {
                        if (web.GetResponseHeader("Location") == string.Empty) throw new Exception("Woops");
                    }
                    catch
                    {
                        loc = false;
                    }
                    finally
                    {
                        if (loc)
                        {
                            HttpWebRequest web2 = (HttpWebRequest)HttpWebRequest.Create(new Uri(web.GetResponseHeader("Location")));
                            web2.Method = "GET";
                            web2.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11";
                            web2.Referer = "http://imgur.com";
                            web2.Headers.Set("Cookie", cc.GetCookieHeader(new Uri("http://imgur.com")));
                            try
                            {
                                Out.WriteDebug("Alternative cookie header: "+ ((HttpWebResponse)web2.GetResponse()).GetResponseHeader("Set-Cookie"));
                            }
                            catch
                            {
                                Out.WriteError("No new cookies");
                            }
                        }
                    }
                    diag.CloseDialog();

                    if (!diag.HasUserCancelled)
                    {

                        if (resp.Contains("Your login information was incorrect"))
                        {
                            errorcode = 1326;
                            return AuthImgur(errorcode);
                        }
                        else
                        {
                            TaskDialog.Show("Your imgur account has been successfully saved", "Authorization succeeded", "Yay!");

                            string header = cc.GetCookieHeader(new Uri("http://imgur.com"));
                            //wc.Headers.Add("Cookie", cc.GetCookieHeader(new Uri("http://imgur.com")));
                            //string aa = wc.DownloadString("http://api.imgur.com/2/account.json?_fake_status=200");
                            return Crypto.EncryptStringAES(header, Core.Secret);
                        }
                    }
                    else return "";
                }

                else errorcode = 1359; //an internal error occured
            }
            return "";
        }
开发者ID:jariz,项目名称:EasyCapture,代码行数:101,代码来源:Credentials.cs

示例13: GetCookieHeader7a

		public void GetCookieHeader7a ()
		{
			CookieContainer cc = new CookieContainer ();
			Cookie cookie = new Cookie ("name1", "value1", "/path", ".mono.com");
			cookie.Comment = "Short name";
			cookie.Expires = DateTime.Now.Add (new TimeSpan (3, 2, 5));
			cookie.Version = 0;
			cc.Add (cookie);
#if RFC2109
			cookie = new Cookie ("name2", "value2", "/path/sub", ".mono.com");
			cookie.Comment = "Description";
			cookie.Expires = DateTime.Now.Add (new TimeSpan (3, 2, 5));
			cookie.Version = 1;
			cc.Add (cookie);
			Assert.AreEqual ("$Version=1; name2=value2; $Path=/path/sub; $Domain=.mono.com; name1=value1", cc.GetCookieHeader (new Uri ("http://live.mono.com/path/sub")), "#A1");
#endif
			Assert.AreEqual ("name1=value1", cc.GetCookieHeader (new Uri ("http://live.mono.com/path")), "#A2");
			Assert.AreEqual (string.Empty, cc.GetCookieHeader (new Uri ("http://live.mono.com/whatever")), "#A3");
			Assert.AreEqual (string.Empty, cc.GetCookieHeader (new Uri ("http://gomono.com/path/sub")), "#A4");
			Assert.AreEqual ("name1=value1", cc.GetCookieHeader (new Uri ("http://mono.com/path/sub")), "#A5");
		}
开发者ID:Profit0004,项目名称:mono,代码行数:21,代码来源:CookieContainerTest.cs

示例14: GetResponseCallback

        private void GetResponseCallback(IAsyncResult asyncResult)
        {
            
            HttpWebResponse response = null;
            try
            {
                response = m_webRequest.EndGetResponse(asyncResult) as HttpWebResponse;
            }
            catch (WebException e)
            {
                LOG.ERROR("EndGetResponse", e);
                response = (HttpWebResponse)e.Response;
                m_code = Convert.ToInt32(response.StatusCode);
            }
            
            Stream stream = response.GetResponseStream();
		    LOG.INFO("openInputStream done");

            CookieContainer container = new CookieContainer();
            container.Add(new Uri(m_strUrl), response.Cookies);
            m_strCookies = container.GetCookieHeader(new Uri(m_strUrl));
			
		    m_code = Convert.ToInt32(response.StatusCode);
            LOG.INFO("getResponseCode : " + m_code);

            readHeaders(m_headers);
            copyHashtable(m_OutHeaders, m_headers);

            try
            {
                if (m_code >= 400)
                {
                    LOG.ERROR("Error retrieving data: " + m_code);
                    if (m_code == Convert.ToInt32(HttpStatusCode.Unauthorized) && m_oSession != null)
                    {
                        LOG.ERROR("Unauthorize error.Client will be logged out");
                        m_oSession.logout();
                    }

                    m_strRespBody = readFully(stream, getResponseEncoding());
                    LOG.TRACE("Response body: " + m_strRespBody);
                }
                else
                {
                    long len = response.ContentLength;
                    LOG.INFO("fetchRemoteData data size:" + len);

                    m_strRespBody = readFully(stream, getResponseEncoding());
                    LOG.INFO("fetchRemoteData data readFully.");
                }
            }
            finally
            {
                stream.Close();
                response.Close();
                m_respWaitEvent.Set();
            }
        }
开发者ID:artemk,项目名称:rhodes,代码行数:58,代码来源:NetRequest.cs

示例15: GetCookieHeader

		public void GetCookieHeader ()
		{
			CookieContainer cc = new CookieContainer ();
			Assert.Throws<ArgumentNullException> (delegate {
				cc.GetCookieHeader (null);
			}, "null");

			Uri uri = new Uri ("http://www.mono-project.com");
			Assert.AreEqual (String.Empty, cc.GetCookieHeader (uri), "none");

			Cookie c1 = new Cookie ();
			c1.Name = "1";
			cc.Add (uri, c1);
			Assert.AreEqual ("1=", cc.GetCookieHeader (uri), "one");

			Cookie c2 = new Cookie ("2", "z");
			cc.Add (uri, c2);
			Assert.AreEqual ("1=; 2=z", cc.GetCookieHeader (uri), "two");

			Cookie c3 = new Cookie ("3", "xy", "/");
			cc.Add (uri, c3);
			Assert.AreEqual ("1=; 2=z; 3=xy", cc.GetCookieHeader (uri), "three");

			c3.HttpOnly = true;
			Assert.AreEqual ("1=; 2=z; 3=xy", cc.GetCookieHeader (uri), "HttpOnly");
		}
开发者ID:dfr0,项目名称:moon,代码行数:26,代码来源:CookieContainerTest.cs


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