示例#1
0
        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);
        }
示例#2
0
        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);
        }
        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
        }
示例#4
0
 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;
     }
 }
示例#5
0
        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;
        }
示例#6
0
 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);
 }
示例#7
0
 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);
 }
    public GetResponseByRequest(string url, string data, CookieContainer ccIn)
    {
        this.url = url;
        this.sendData = data;
        this.cc = ccIn;

        this.requestTimeout = 120000; //iki deqiqe;
    }
        public static void MaxCookieSize_GetSet_Success()
        {
            CookieContainer cc = new CookieContainer();
            Assert.Equal(CookieContainer.DefaultCookieLengthLimit, cc.MaxCookieSize);

            cc.MaxCookieSize = 8192;
            Assert.Equal(8192, cc.MaxCookieSize);
        }
示例#10
0
文件: test.cs 项目: mono/gert
	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 ();
	}
示例#11
0
        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
        }
示例#12
0
        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));
        }
示例#13
0
    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;
    }
示例#14
0
        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);
        }
示例#15
0
文件: test.cs 项目: mono/gert
	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;
	}
示例#16
0
文件: test.cs 项目: mono/gert
	static int Main ()
	{
		string baseDir = AppDomain.CurrentDomain.BaseDirectory;
		string webDir = Path.Combine (baseDir, "web");

		CookieContainer cookies = new CookieContainer ();

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

		DateTime start = DateTime.Now;

		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>Index</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;
		}

		Assert.IsTrue (File.Exists (Path.Combine (webDir, "session_start")), "#B1");
		Assert.IsFalse (File.Exists (Path.Combine (webDir, "session_end")), "#B2");

		TimeSpan totalSessionTime;

		while (true) {
			Thread.Sleep (1000);
			totalSessionTime = DateTime.Now - start;
			if (File.Exists (Path.Combine (webDir, "session_end")))
				break;
			if (totalSessionTime.TotalSeconds > 180)
				break;
		}

		Assert.IsTrue (totalSessionTime.TotalSeconds > 60, "#C1:" + totalSessionTime.TotalSeconds);
		Assert.IsTrue (totalSessionTime.TotalSeconds < 150, "#C2:" + totalSessionTime.TotalSeconds);

		return 0;
	}
        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;
        }        
示例#18
0
    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);
    }
示例#19
0
 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);*/
 }
示例#20
0
        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);
        }
示例#21
0
    public static bool ExecLogin(string name,string pass)
    {
        bool result = false;
        string password = GetMd5Str32(pass).ToUpper(); 
        string padata = "username="******"&pwd=" + password + "&imgcode=&f=json";
        string url = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN ";//请求登录的URL
        try
        {
            CookieContainer cc = new CookieContainer();//接收缓存
            byte[] byteArray = Encoding.UTF8.GetBytes(padata); // 转化
            HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url);  //新建一个WebRequest对象用来请求或者响应url
            webRequest2.Referer = "https://mp.weixin.qq.com/cgi-bin/loginpage?lang=zh_CN&t=wxm2-login";
            webRequest2.CookieContainer = cc;                                      //保存cookie  
            webRequest2.Method = "POST";                                          //请求方式是POST
            webRequest2.ContentType = "application/x-www-form-urlencoded";       //请求的内容格式为application/x-www-form-urlencoded
            webRequest2.ContentLength = byteArray.Length;
          
            Stream newStream = webRequest2.GetRequestStream();           //返回用于将数据写入 Internet 资源的 Stream。
            // Send the data.
            newStream.Write(byteArray, 0, byteArray.Length);    //写入参数
            newStream.Close();
            HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
            StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default);
            string text2 = sr2.ReadToEnd();

            //此处用到了newtonsoft来序列化
            WeiXinRetInfo retinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<WeiXinRetInfo>(text2);
            string token = string.Empty;
            if (retinfo.base_resp.ret==0)
            {
                token = retinfo.redirect_url.Split(new char[] { '&' })[2].Split(new char[] { '=' })[1].ToString();//取得令牌
                Caching.Set("LoginCookie", cc,300);
                Caching.Set("CreateDate", DateTime.Now, 300);
                Caching.Set("Token", token,300);
                LoginInfo.LoginCookie = cc;
                LoginInfo.CreateDate = DateTime.Now;
                LoginInfo.Token = token;
                result = true;
            }
        }
        catch (Exception ex)
        {
          
            throw new Exception(ex.StackTrace);
        }
        return result;
    }
示例#22
0
    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;
    }
示例#23
0
 public static string SteamWebRequest(CookieContainer cookie, string url, string data = null, string lasturl = "")
 {
     HttpWebResponse httpWebResponse = (HttpWebResponse) null;
     StreamReader streamReader = (StreamReader) null;
     HttpWebRequest httpWebRequest1 = (HttpWebRequest) null;
     try
     {
       httpWebRequest1 = (HttpWebRequest) null;
       HttpWebRequest httpWebRequest2 = !url.StartsWith("http") ? (HttpWebRequest) WebRequest.Create("http" + (data != null ? "s" : "") + "://steamcommunity.com/" + url) : (HttpWebRequest) WebRequest.Create(url);
       httpWebRequest2.Referer = "http://steamcommunity.com/" + lasturl;
       httpWebRequest2.Accept = data != null ? "*/*" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
       httpWebRequest2.Method = data != null ? "POST" : "GET";
       if (data != null)
     httpWebRequest2.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
       ((NameValueCollection) httpWebRequest2.Headers)["Accept-Charset"] = "iso-8859-1,*,utf-8";
       ((NameValueCollection) httpWebRequest2.Headers)["Origin"] = "https://steamcommunity.com";
       httpWebRequest2.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.3; en-US; Valve Steam Client/1393366296; ) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19";
       ((NameValueCollection) httpWebRequest2.Headers)["Accept-Language"] = "en-us,en";
       ((NameValueCollection) httpWebRequest2.Headers)["Accept-Encoding"] = "gzip,deflate";
       httpWebRequest2.CookieContainer = cookie;
       httpWebRequest2.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
       if (data != null)
       {
     using (StreamWriter streamWriter = new StreamWriter(((WebRequest) httpWebRequest2).GetRequestStream()))
       streamWriter.Write(data);
       }
       httpWebResponse = (HttpWebResponse) httpWebRequest2.GetResponse();
       if (httpWebResponse.StatusCode == HttpStatusCode.OK)
       {
     streamReader = new StreamReader(httpWebResponse.GetResponseStream());
     return streamReader.ReadToEnd();
       }
     }
     catch (WebException ex)
     {
       if (ex.Response != null)
     return new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
     }
     finally
     {
       if (streamReader != null)
     streamReader.Close();
       if (httpWebResponse != null)
     httpWebResponse.Close();
     }
     return (string) null;
 }
示例#24
0
        public HttpClientChannel()
        {
            this.getRequestStreamCallback = GetRequestStreamCallback;
            this.getResponseCallback = GetResponseCallback;

            // Set HWR default values
            this.allowAutoRedirect = true;
            this.maxRequestContentBufferSize = HttpContent.DefaultMaxBufferSize;
            this.automaticDecompression = DecompressionMethods.None;
            this.clientCertificates = null; // only create collection when required.
            this.cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies.
            this.credentials = null;
            this.maxAutomaticRedirections = 50;
            this.preAuthenticate = false;
            this.proxy = null;
            this.useProxy = true;
            this.useCookies = true; // deal with cookies by default.
            this.useDefaultCredentials = false;
        }
 public static bool ObtainsessionID(CookieContainer cookie)
 {
     HttpWebResponse response = null;
     StreamReader reader = null;
     HttpWebRequest request = null;
     try
     {
         request = (HttpWebRequest) WebRequest.Create("http://steamcommunity.com");
         request.Method = "GET";
         request.Headers["Origin"] = "http://steamcommunity.com";
         request.Referer = "http://steamcommunity.com";
         request.Headers["Accept-Encoding"] = "gzip,deflate";
         request.Headers["Accept-Language"] = "en-us,en";
         request.Headers["Accept-Charset"] = "iso-8859-1,*,utf-8";
         request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.3; en-US; Valve Steam Client/1393366296; ) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19";
         request.CookieContainer = cookie;
         request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
         request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
         response = (HttpWebResponse) request.GetResponse();
         if (response.StatusCode == HttpStatusCode.OK)
         {
             reader = new StreamReader(response.GetResponseStream());
             string str = reader.ReadToEnd();
             return !(reader.ReadToEnd().Contains("g_steamID = false;") || (response.Cookies["sessionid"] == null));
         }
     }
     catch (Exception)
     {
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
         }
         if (response != null)
         {
             response.Close();
         }
     }
     return false;
 }
示例#26
0
    private static Cookie setWatchTicket(string watchId, ref string thumbplaykey, ref string response, ref string p)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://ext.nicovideo.jp/thumb_watch/" + watchId);
        HttpWebResponse res = null;

        req.Referer = "http://www.kazukikuroda.co.cc/";
        CookieContainer ctor = new CookieContainer();
        req.CookieContainer = ctor;
        res = (HttpWebResponse)req.GetResponse();
        string responsedData = null;
        using (System.IO.StreamReader strm = new System.IO.StreamReader(res.GetResponseStream())) {
            responsedData = strm.ReadToEnd();
            p = responsedData;
        }
        //Regexオブジェクトを作成
        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("(?<=\\'thumbPlayKey\\'\\: )\\'.+?\\'", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        System.Text.RegularExpressions.MatchCollection mc = r.Matches(responsedData);
        thumbplaykey = mc[0].Value.Replace("'", "");
        r = new System.Text.RegularExpressions.Regex("(?<=Nicovideo\\.playerUrl = )\\'.+?\\'");
        mc = r.Matches(responsedData);
        string referer = mc[0].Value.Replace("'", "");

        req = (HttpWebRequest)WebRequest.Create("http://ext.nicovideo.jp/thumb_watch");
        req.CookieContainer = ctor;
        req.Headers.Add(System.Net.HttpRequestHeader.AcceptLanguage, "ja,en-US;q=0.8,en;q=0.6");
        req.ContentType = "application/x-www-form-urlencoded";
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1";
        req.Method = "post";
        req.KeepAlive = true;
        req.Referer = referer;
        var _with1 = new System.IO.StreamWriter(req.GetRequestStream());
        string post = Uri.EscapeUriString(string.Format("as3=1&k={0}&v={1}", thumbplaykey, watchId));
        _with1.Write(post);
        _with1.Close();
        res = (HttpWebResponse)req.GetResponse();
        using (System.IO.StreamReader strm = new System.IO.StreamReader(res.GetResponseStream())) {
            response = strm.ReadToEnd();
        }

        return res.Cookies["nicohistory"];
    }
示例#27
0
文件: test.cs 项目: mono/gert
	static bool ExecuteRequest (CookieContainer container, int expectedCounter)
	{
		HttpWebRequest request = (HttpWebRequest) WebRequest.Create ("http://localhost:8081/index.aspx");
		request.CookieContainer = container;
		request.Method = "GET";

		HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
		using (StreamReader sr = new StreamReader (response.GetResponseStream (), Encoding.UTF8, true)) {
			string result = sr.ReadToEnd ();
			string expected = string.Format (CultureInfo.InvariantCulture,
				"<span id=\"CounterLabel\">{0}</span>",
				expectedCounter);
			if (result.IndexOf (expected) == -1) {
				Console.WriteLine (result);
				return false;
			}
		}
		response.Close ();

		return true;
	}
示例#28
0
文件: test.cs 项目: mono/gert
	static int Main ()
	{
		CookieContainer container = new CookieContainer ();

		if (!ExecuteRequest (container, 1))
			return 1;

		if (!ExecuteRequest (container, 2))
			return 2;

		if (!ExecuteRequest (new CookieContainer (), 1))
			return 3;

		if (!ExecuteRequest (container, 3))
			return 4;

		EndSession (container);

		if (!ExecuteRequest (container, 1))
			return 5;

		return 0;
	}
示例#29
0
 public static CookieCollection CookieInfo(String str)
 {
     CookieContainer CC = new CookieContainer();
     HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(str);
     Req.Proxy = null;
     Req.UseDefaultCredentials = true;
     //YOU MUST ASSIGN A COOKIE CONTAINER FOR THE REQUEST TO PULL THE COOKIES
     Req.CookieContainer = CC;
     HttpWebResponse Res = (HttpWebResponse)Req.GetResponse();
     //DUMP THE COOKIES
     Console.WriteLine("----- COOKIES -----");
     if(Res.Cookies != null &&  Res.Cookies.Count != 0)
     {
         foreach(Cookie c in Res.Cookies)
         {
          Console.WriteLine("\t" + c.ToString());
         }
     }
     else
     {
         Console.WriteLine("No Cookies");
     }
     return Res.Cookies;
 }
示例#30
0
 public CookieClient()
 {
     Cookie   = GenerateCookies();
     Encoding = Encoding.UTF8;
 }
示例#31
0
 public GoogleClient()
 {
     _Container = new CookieContainer();
 }
示例#32
0
        public HttpWebResponse HttpPostMethod(string RequestUri, string PostReferer, byte[] PostBytes, CookieContainer RetrievedCookies)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(RequestUri);

            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept      = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            httpWebRequest.Headers.Add("Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4");
            httpWebRequest.Method            = "POST";
            httpWebRequest.Referer           = PostReferer;
            httpWebRequest.AllowAutoRedirect = false;
            httpWebRequest.CookieContainer   = new CookieContainer();
            httpWebRequest.CookieContainer   = RetrievedCookies;
            Stream requestStream = httpWebRequest.GetRequestStream();

            requestStream.Write(PostBytes, 0, PostBytes.Length);
            requestStream.Flush();
            requestStream.Close();
            return((HttpWebResponse)httpWebRequest.GetResponse());
        }
 private void SetClientCookie(CookieContainer cookieContainer)
 {
     cookieContainer.Add(_baseRequestUri, new Cookie(VSphereUrlCookie, _vSphereUrl));
     cookieContainer.Add(_baseRequestUri, new Cookie(VSphereSessionIdCookie, _vSphereSessionId));
 }
示例#34
0
 public WebClientSession(CookieContainer container)
 {
     this.container = container;
 }
示例#35
0
        private void MatFessorForm_Load(object sender, EventArgs e)
        {
            CertMaker.createRootCert();
            CertMaker.trustRootCert();

            FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oSession)
            {
                oSession.bBufferResponse = true;
            };

            FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;

            FiddlerApplication.Startup(8888, true, true, true);

            new Thread(async() =>
            {
                while (true)
                {
                    Thread.Sleep(50);

                    if (cookies != null)
                    {
                        if (!chkSpamAdaptiveTrainingAnswers.Checked)
                        {
                            continue;
                        }

                        // Spam Thread
                        //new Thread(async () =>
                        //{
                        var baseAddress     = new Uri("https://www.matematikfessor.dk");
                        var cookieContainer = new CookieContainer();
                        using (var handler = new HttpClientHandler()
                        {
                            CookieContainer = cookieContainer
                        })

                            using (var client = new HttpClient(handler)
                            {
                                BaseAddress = baseAddress
                            })
                            {
                                var values = new Dictionary <string, string>
                                {
                                    { "data[Test][question_id]", "747884" },
                                    { "data[Test][result_iae_data]", "{\"chosen_answers\":[{\"value\":57}]}" }
                                };

                                var content = new FormUrlEncodedContent(values);

                                string[] szSplitCookies = cookies.Split(';');

                                cookieContainer.Add(baseAddress, new Cookie("__cfduid", szSplitCookies[0].Split('=')[1]));
                                cookieContainer.Add(baseAddress, new Cookie("CAKEPHP", szSplitCookies[1].Split('=')[1]));


                                var postResult = await client.PostAsync("/adaptive_test/save_answer", content);

                                string htmlResult = await postResult.Content.ReadAsStringAsync();
                                Debug.WriteLine(htmlResult);

                                SentAnswer();
                            }
                        //}).Start();
                    }
                }
            }).Start();
        }
 public WebCrawlerSourceNode(string[] rootUrls, XMLEntityModel entityModel, CookieContainer cookieContainer = null, params string[] urlPatterns)
     : this(rootUrls, entityModel, (content, url) => GetUrlsFromHtmlByPatterns(content, url, urlPatterns), cookieContainer)
 {
 }
示例#37
0
 public WebClientSession()
 {
     container = new CookieContainer();
 }
示例#38
0
 public GoogleClient(CookieContainer container)
 {
     _Container = container;
 }
示例#39
0
 public CookieWebRequest()
 {
     this.cookieContainer = new CookieContainer();
 }
示例#40
0
 private void method_0(string string_0, string string_1, CookieContainer cookieContainer_1)
 {
     this.cookies = cookieContainer_1;
     this.DownloadFile(string_0, string_1);
 }
示例#41
0
 public static CookieContainerBuilder Create(CookieContainer cookies)
 {
     return(new CookieContainerBuilder(cookies));
 }
示例#42
0
 private CookieContainerBuilder(CookieContainer cookieContainer)
 {
     _cookieContainer = cookieContainer;
 }
示例#43
0
 public static void SetHttpCookiesContainer(this ScenarioContext scenarioContext, CookieContainer cookieContainer)
 {
     scenarioContext.Set(cookieContainer, HttpCookiesContainerKey);
 }
示例#44
0
 public FormClient(CookieContainer cookies)
 {
     this.Cookies = cookies;
     this.Items   = new List <FormItem> ();
 }
示例#45
0
 public CookieAwareWebClient()
 {
     CookieContainer = new CookieContainer();
     ResponseCookies = new CookieCollection();
 }
示例#46
0
 /// <summary>
 /// 创建一个新的 WebClient 实例。
 /// </summary>
 /// <param name="cookies">Cookie 容器</param>
 public MyWebClient(CookieContainer cookies)
 {
     this._cookieContainer = cookies;
 }
示例#47
0
        //接口登录POST,登录成功后把账号密码或Token\sessionid\jsessionid写入CookieContainer
        public string HttpPostLogin(string url, string postData, CookieContainer cookies)
        {
            //定义request并设置request的路径
            // WebRequest request = WebRequest.Create(url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            if (cookies.Count == 0)
            {
                request.CookieContainer = new CookieContainer();
                cookies = request.CookieContainer;
            }
            else
            {
                request.CookieContainer = cookies;
            }
            //  request.CookieContainer = cookies;
            request.Method = "POST";

            //初始化request参数
            // string postData = "{ ID: \"1\", NAME: \"Jim\", CREATETIME: \"1988-09-11\" }";

            //设置参数的编码格式,解决中文乱码
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //设置request的MIME类型及内容长度
            request.ContentType = "application/json";
            //  request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            request.ContentLength = byteArray.Length;
            //打开request字符流
            Stream dataStream = request.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //定义response为前面的request响应
            // WebResponse response = request.GetResponse();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (cookies.Count == 0)
            {
                response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                CookieCollection cook;
                cook = response.Cookies;
                cookies.Add(cook);
            }
            //Console.WriteLine(response.Headers.Get("Set-Cookie"));
            //获取相应的状态代码
            //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            //定义response字符流
            dataStream = response.GetResponseStream();
            StreamReader reader             = new StreamReader(dataStream);
            string       responseFromServer = reader.ReadToEnd();//读取所有

            //----系统有Token\sessionid\jsessionid认证,但是接口未提供Token的返回值,需要从回应头中自己解析取Token码的情况
            //JObject jresponse = JObject.Parse(responseFromServer);
            //if (jresponse["code"].ToString() == "200")//登录成功后
            //{
            //    //读取回应头的Token\sessionid\jsessionid
            //    return response.Headers.Get("Set-Cookie");
            //}
            //else
            //{
            //    return responseFromServer;
            //}
            //----end-----
            return(responseFromServer);
        }
示例#48
0
 public ClientFormsIdentity(string name, string password, MembershipProvider provider, string authenticationType, bool isAuthenticated, CookieContainer authenticationCookies)
 {
     Password              = password;
     Name                  = name;
     Provider              = provider;
     AuthenticationType    = authenticationType;
     IsAuthenticated       = isAuthenticated;
     AuthenticationCookies = authenticationCookies;
 }
        public WebCrawlerSourceNode(string[] rootUrls, XMLEntityModel entityModel, Func <string, string, IEnumerable <string> > discoverCrawlerUrls, CookieContainer cookieContainer = null)
        {
            _NextUrlQueue = new ConcurrentQueue <string>();
            foreach (string rootUrl in rootUrls)
            {
                _NextUrlQueue.Enqueue(rootUrl);
                VisitedUrls.Add(rootUrl);
            }

            EntityModel         = entityModel;
            DiscoverCrawlerUrls = discoverCrawlerUrls;
            _CookieContainer    = cookieContainer;
        }
示例#50
0
        private bool isHtml5Login(CookieContainer cc, string url)
        {
            var c = cc.GetCookieHeader(new Uri(url));
            //for (var i = 0; i < 1; i++) {

            /*
             * var headers = new WebHeaderCollection();
             * try {
             *      util.debugWriteLine("ishtml5login getpage " + url + util.getMainSubStr(isSub));
             * //					ar _url = (isRtmp) ? ("https://live.nicovideo.jp/api/getplayerstatus/" + util.getRegGroup(url, "(lv\\d+)")) : url;
             *      pageSource = util.getPageSource(_url, ref headers, cc);
             * //					util.debugWriteLine(cc.GetCookieHeader(new Uri(_url)));
             *      util.debugWriteLine("ishtml5login getpage ok" + util.getMainSubStr(isSub));
             * } catch (Exception e) {
             *      util.debugWriteLine("cookiegetter ishtml5login " + e.Message+e.StackTrace + util.getMainSubStr(isSub));
             *      pageSource = "";
             *      log += "ページの取得中にエラーが発生しました。" + e.Message + e.Source + e.TargetSite + e.StackTrace;
             *      continue;
             * }
             * //			isHtml5 = (headers.Get("Location") == null) ? false : true;
             * if (pageSource == null) {
             *      log += "ページが取得できませんでした。";
             *      util.debugWriteLine("not get page" + util.getMainSubStr(isSub));
             *      continue;
             * }
             * var isLogin = !(pageSource.IndexOf("\"login_status\":\"login\"") < 0 &&
             *      pageSource.IndexOf("login_status = 'login'") < 0);
             *
             */

            //test
            //test(cc, url);

            var isLogin = false;
            //var isFollow = false;
            string uid = null;

            try {
                var fl = new FollowChecker(form, cc).getFollowList(new bool[] { true, false, false }, false);
                if (fl == null)
                {
                    return(false);
                }

                var us = cc.GetCookies(new Uri(url))["user_session"];
                uid = us == null ? null : util.getRegGroup(us.Value, "user_session_(.+?)_");
                //form.addLogText("usersession " + (us != null) + " uid " + (uid != null));

                if (uid != null)
                {
                    var _url = "https://public.api.nicovideo.jp/v1/user/followees/niconico-users/" + uid + ".json";
                    var res  = util.getPageSource(_url, cc);
                    //form.addLogText("cookie check " + (res != null));

                    //var n = util.getUserName(uid, out isFollow, cc, true);
                    if (res != null)
                    {
                        isLogin = true;
                    }


                    if (!isLogin)
                    {
                        //test0
                        util.debugWriteLine("access__ isHtml5Login 0 ");
                        var _req = (HttpWebRequest)WebRequest.Create("https://www.nicovideo.jp/my/channel");
                        _req.Proxy           = null;
                        _req.CookieContainer = cc;
                        _req.Headers.Add("Accept-Encoding", "gzip,deflate");
                        _req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                        //_req.CookieContainer = new CookieContainer();
                        try {
                            using (var r = (HttpWebResponse)_req.GetResponse())
                                using (var _r = r.GetResponseStream())
                                    using (var __sr = new System.IO.StreamReader(_r)) {
                                        var __r = __sr.ReadToEnd();
                                        //util.debugWriteLine("__r + " + __r);
                                        us = _req.CookieContainer.GetCookies(new Uri("https://www.nicovideo.jp/my/channel"))["user_session"];
                                        if (__r != null)
                                        {
                                            isLogin = true;
                                        }
                                        //form.addLogText("cookie check3 " + isLogin + " " + (us != null));
                                        util.debugWriteLine(isLogin);
                                    }
                        } catch (Exception ee) {
                            util.debugWriteLine(ee.Message + ee.Source + ee.StackTrace + ee.TargetSite);
                            //form.addLogText("cookie check3 exception");
                        }
                    }
                    //test0
                }
            } catch (Exception e) {
                util.debugWriteLine(e.Message + e.Source + e.StackTrace + e.TargetSite);
            }

            util.debugWriteLine("islogin " + isLogin);
            log += (isLogin) ? "ログインに成功しました。" : "ログインに失敗しました";
            //			if (!isLogin) log += pageSource;
            if (isLogin)
            {
                //				id = (isRtmp) ? util.getRegGroup(pageSource, "<user_id>(\\d+)</user_id>")
                //					: util.getRegGroup(pageSource, "\"user_id\":(\\d+)");
                //id = util.getRegGroup(pageSource, "\"user_id\":(\\d+)");
                //if (id == null) id = util.getRegGroup(pageSource, "user_id = (\\d+)");
                util.debugWriteLine("id " + uid);
            }
            else
            {
                util.debugWriteLine("not login " + uid);
            }
            return(isLogin);
            //}
            //return false;
        }
示例#51
0
 public webAccessUtilities()
 {
     // initialize variables
     cookieJar = new CookieContainer();
 }
示例#52
0
 public static void Ctor_Capacity_Success()
 {
     CookieContainer cc = new CookieContainer(5);
     Assert.Equal(5, cc.Capacity);
 }
示例#53
0
 public MyWebClient(int timeoutSeconds)
 {
     this._cookieContainer = new CookieContainer();
     this._cookieList      = new NameValueCollection();
     this._timeoutSeconds  = timeoutSeconds;
 }
示例#54
0
        private HttpWebRequest GenerateRequest(ConnectionOptions co)
        {
            var request = (HttpWebRequest)WebRequest.Create(co.source);

            // set user agent
            if (!string.IsNullOrEmpty(co.userAgent))
            {
                request.UserAgent = co.userAgent;
            }

            // set proxy
            if (co.proxy != null)
            {
                request.Proxy = co.proxy;
            }

            if (co.useHttp10)
            {
                request.ProtocolVersion = HttpVersion.Version10;
            }

            // set timeout value for the request
            request.Timeout                   = request.ServicePoint.ConnectionLeaseTimeout = request.ServicePoint.MaxIdleTime = co.requestTimeout;
            request.AllowAutoRedirect         = true;
            request.AllowWriteStreamBuffering = true;
            request.AllowAutoRedirect         = true;
            request.KeepAlive                 = true;
            request.SendChunked               = false;

            // set login and password
            if (!string.IsNullOrEmpty(co.username))
            {
                request.Credentials = new NetworkCredential(co.username, co.password);
            }
            // set connection group name
            if (co.useSeparateConnectionGroup)
            {
                request.ConnectionGroupName = request.GetHashCode().ToString(CultureInfo.InvariantCulture);
            }
            // force basic authentication through extra headers if required

            var authInfo = "";

            if (!string.IsNullOrEmpty(co.username))
            {
                authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(co.username + ":" + co.password));
                request.Headers["Authorization"] = "Basic " + authInfo;
            }


            if (!string.IsNullOrEmpty(co.cookies))
            {
                co.cookies = co.cookies.Replace("[AUTH]", authInfo);
                co.cookies = co.cookies.Replace("[USERNAME]", co.username);
                co.cookies = co.cookies.Replace("[PASSWORD]", co.password);
                co.cookies = co.cookies.Replace("[CHANNEL]", co.channel);
                var      myContainer = new CookieContainer();
                string[] coll        = co.cookies.Split(';');
                foreach (var ckie in coll)
                {
                    if (!string.IsNullOrEmpty(ckie))
                    {
                        string[] nv = ckie.Split('=');
                        if (nv.Length == 2)
                        {
                            var cookie = new Cookie(nv[0].Trim(), nv[1].Trim());
                            myContainer.Add(new Uri(request.RequestUri.ToString()), cookie);
                        }
                    }
                }
                request.CookieContainer = myContainer;
            }

            if (!string.IsNullOrEmpty(co.headers))
            {
                co.headers = co.headers.Replace("[AUTH]", authInfo);
                string[] coll = co.headers.Split(';');
                foreach (var hdr in coll)
                {
                    if (!string.IsNullOrEmpty(hdr))
                    {
                        string[] nv = hdr.Split('=');
                        if (nv.Length == 2)
                        {
                            request.Headers.Add(nv[0], nv[1]);
                        }
                    }
                }
            }
            return(request);
        }
示例#55
0
        async public Task <CookieContainer[]> getHtml5RecordCookie(string url, bool isSub)
        {
            CookieContainer cc;

            if (!isSub)
            {
                cc = await getCookieContainer(cfg.get("BrowserNum"),
                                              cfg.get("issecondlogin"), cfg.get("accountId"),
                                              cfg.get("accountPass"), cfg.get("user_session"),
                                              cfg.get("user_session_secure"), false,
                                              url);

                if (cc != null)
                {
                    var c        = cc.GetCookies(TargetUrl)["user_session"];
                    var secureC  = cc.GetCookies(TargetUrl)["user_session_secure"];
                    var age_auth = cc.GetCookies(TargetUrl)["age_auth"];

                    var l = new List <KeyValuePair <string, string> >();
                    if (c != null)
                    {
//						cfg.set("user_session", c.Value);
                        l.Add(new KeyValuePair <string, string>("user_session", c.Value));
                    }
                    if (secureC != null)
                    {
//						cfg.set("user_session_secure", secureC.Value);
                        l.Add(new KeyValuePair <string, string>("user_session_secure", secureC.Value));
                    }
                    if (age_auth != null)
                    {
                        l.Add(new KeyValuePair <string, string>("age_auth", age_auth.Value));
                    }
                    cfg.set(l);
                }
            }
            else
            {
                cc = await getCookieContainer(cfg.get("BrowserNum2"),
                                              cfg.get("issecondlogin2"), cfg.get("accountId2"),
                                              cfg.get("accountPass2"), cfg.get("user_session2"),
                                              cfg.get("user_session_secure2"), true,
                                              url);

                if (cc != null)
                {
                    var c        = cc.GetCookies(TargetUrl)["user_session2"];
                    var secureC  = cc.GetCookies(TargetUrl)["user_session_secure2"];
                    var age_auth = cc.GetCookies(TargetUrl)["age_auth"];

                    var l = new List <KeyValuePair <string, string> >();
                    if (c != null)
                    {
//						cfg.set("user_session2", c.Value);
                        l.Add(new KeyValuePair <string, string>("user_session2", c.Value));
                    }
                    if (secureC != null)
                    {
//						cfg.set("user_session_secure2", secureC.Value);
                        l.Add(new KeyValuePair <string, string>("user_session_secure2", secureC.Value));
                    }
                    l.Add(new KeyValuePair <string, string>("age_auth", age_auth.Value));
                    cfg.set(l);
                }
            }

            var ret = new CookieContainer[] { cc };

            return(ret);
        }
示例#56
0
 /// <summary>
 /// 创建一个新的 WebClient 实例。
 /// </summary>
 public MyWebClient()
 {
     this._cookieContainer = new CookieContainer();
     this._cookieList      = new NameValueCollection();
 }
示例#57
0
        async private Task <CookieContainer> getBrowserCookie(bool isSub)
        {
            var si = SourceInfoSerialize.load(isSub);

            if (si == null)
            {
                return(null);
            }

//			var importer = await SunokoLibrary.Application.CookieGetters.Default.GetInstanceAsync(si, false);
            ICookieImporter importer = await SunokoLibrary.Application.CookieGetters.Default.GetInstanceAsync(si, false).ConfigureAwait(false);

//			var importers = new SunokoLibrary.Application.CookieGetters(true, null);
//			var importera = (await SunokoLibrary.Application.CookieGetters.Browsers.IEProtected.GetCookiesAsync(TargetUrl));
//			foreach (var rr in importer.Cookies)
//				util.debugWriteLine(rr);
            //importer = await importers.GetInstanceAsync(si, true);
            if (importer == null)
            {
                return(null);
            }


            CookieImportResult result = await importer.GetCookiesAsync(TargetUrl).ConfigureAwait(false);

            if (result.Status != CookieImportState.Success)
            {
                return(null);
            }

            //if (result.Cookies["user_session"] == null) return null;
            //var cookie = result.Cookies["user_session"].Value;

            //util.debugWriteLine("usersession " + cookie);

            var requireCookies = new List <Cookie>();
            var cc             = new CookieContainer();

            cc.PerDomainCapacity = 200;
            foreach (Cookie _c in result.Cookies)
            {
                try {
                    //cc.Add(_c);
                    if (_c.Name == "age_auth" || _c.Name.IndexOf("user_session") > -1)
                    {
                        requireCookies.Add(new Cookie(_c.Name, _c.Value, "/", ".nicovideo.jp"));
                    }
                } catch (Exception e) {
                    util.debugWriteLine("cookie add browser " + _c.ToString() + e.Message + e.Source + e.StackTrace + e.TargetSite + util.getMainSubStr(isSub));
                }
            }
//			result.AddTo(cc);
            foreach (var _c in requireCookies)
            {
                cc.Add(_c);
            }

            var c       = cc.GetCookies(TargetUrl)["user_session"];
            var secureC = cc.GetCookies(TargetUrl)["user_session_secure"];

            cc = setUserSession(cc, c, secureC);


            return(cc);
        }
示例#58
0
文件: Form1.cs 项目: smagician/hebgb
 private bool LogIn()
 {
     try
     {
         string         requestUriString = "http://www.hebgb.gov.cn/portal/j_security_check";
         HttpWebRequest httpWebRequest   = (HttpWebRequest)WebRequest.Create(requestUriString);
         httpWebRequest.Method            = "POST";
         httpWebRequest.Accept            = "*/*;";
         httpWebRequest.UserAgent         = this.webuserAgent;
         httpWebRequest.ContentType       = "application/x-www-form-urlencoded";
         httpWebRequest.AllowAutoRedirect = true;
         httpWebRequest.CookieContainer   = this.cookieContainer_0;
         httpWebRequest.KeepAlive         = false;
         httpWebRequest.ProtocolVersion   = HttpVersion.Version10;
         string s = string.Format("j_uri=%2Fportal%2Findex%21index.action&yzm=not&j_username={0}++&j_password={1}&imgcode=",
                                  this.textBox_UserName.Text,
                                  this.textBox_Password.Text);
         byte[] bytes = Encoding.UTF8.GetBytes(s);
         httpWebRequest.ContentLength = (long)bytes.Length;
         httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
         HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
         StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
         string          text            = streamReader.ReadToEnd();
         httpWebResponse.Close();
         streamReader.Close();
         httpWebRequest.Abort();
         httpWebResponse.Close();
         this.cookieContainer_0 = httpWebRequest.CookieContainer;
         if (text.Contains("欢迎您"))
         {
             this.button1.Text             = "登录成功";
             this.textBox_UserName.Enabled = false;
             this.textBox_Password.Enabled = false;
             this.button1.Enabled          = false;
             Thread.Sleep(1000);
             return(true);
         }
         else
         {
             if (text.Contains("验证码输入错误"))
             {
                 MessageBox.Show("登录失败!四位的数字验证码输入错误!");
                 return(false);
             }
             if (text.Contains("用户名或密码输入错误"))
             {
                 MessageBox.Show("登录失败!用户名或密码输入错误!请先上官网 www.hebgb.gov.cn 验证一下!也可能是网站升级造成登录失败。");
                 return(false);
             }
         }
     }
     catch (Exception ex)
     {
         this.Text = ex.Message.ToString();
         if (ex.Message.Contains("500"))
         {
             MessageBox.Show("帐号登录状态异常1,请重新登录!期间不要在外面的浏览器登录帐号,不然会挤掉本程序的登录,造成学习失效!");
         }
         else if (ex.Message.Contains("操时"))
         {
             MessageBox.Show("登录操时!");
         }
         else
         {
             MessageBox.Show(ex.ToString());
         }
     }
     return(false);
 }
示例#59
0
 public FormClient()
 {
     this.Items   = new List <FormItem> ();
     this.Cookies = new CookieContainer();
 }
示例#60
0
 public CookieAwareWebClient(CookieContainer cookies)
 {
     this.CookieContainer = cookies;
 }