Inheritance: IWebProxy, ISerializable
示例#1
0
        public string POSTNFC(string url, string query, string auth)
        {
            HttpWebRequest hwrq = CreateRequest(url);

            hwrq.CookieContainer = Cookies;
            hwrq.Method          = "DELETE";
            hwrq.ContentType     = "application/x-www-form-urlencoded";
            WebHeaderCollection webHeaderCollection = new System.Net.WebHeaderCollection();
            Decryptor           decryptor           = new Decryptor("ckuJ1YQrX7ysO/WVHkowGA==");

            hwrq.Credentials = new NetworkCredential("d.astahov", decryptor.DescryptStr, "GRADIENT");
            WebProxy proxy = new System.Net.WebProxy("proxy-dc.gradient.ru", 3128);

            proxy.Credentials = hwrq.Credentials;
            hwrq.Proxy        = proxy;
            webHeaderCollection.Add(System.Net.HttpRequestHeader.Authorization, string.Format("token {0}", auth));
            hwrq.Headers.Add(webHeaderCollection);
            byte[] data = Encoding.UTF8.GetBytes(query);
            hwrq.ContentLength = data.Length;
            hwrq.GetRequestStream().Write(data, 0, data.Length);
            using (HttpWebResponse hwrs = (HttpWebResponse)hwrq.GetResponse())
            {
                Cookies.Add(hwrs.Cookies);
                using (StreamReader sr = new StreamReader(hwrs.GetResponseStream(), Encoding.Default))
                {
                    return(hwrs.Headers.ToString() + sr.ReadToEnd().Trim());
                }
            }
        }
示例#2
0
        public string POSTLogin(string url, string userName, string password)
        {
            HttpWebRequest hwrq = CreateRequest(url);

            hwrq.CookieContainer = Cookies;
            hwrq.Method          = "POST";
            Decryptor decryptor = new Decryptor("ckuJ1YQrX7ysO/WVHkowGA==");

            hwrq.Credentials = new NetworkCredential("d.astahov", decryptor.DescryptStr, "GRADIENT");
            hwrq.ContentType = "application/json";

            WebProxy proxy = new System.Net.WebProxy("proxy-dc.gradient.ru", 3128);

            proxy.Credentials = hwrq.Credentials;
            hwrq.Proxy        = proxy;
            string query = "{";

            query += string.Format(" \"userName\":\"{0}\", \"password\":\"{1}\" ", userName, password);
            query += "}";

            byte[] data = Encoding.UTF8.GetBytes(query);
            hwrq.ContentLength = data.Length;
            hwrq.GetRequestStream().Write(data, 0, data.Length);
            using (HttpWebResponse hwrs = (HttpWebResponse)hwrq.GetResponse())
            {
                Cookies.Add(hwrs.Cookies);
                using (StreamReader sr = new StreamReader(hwrs.GetResponseStream(), Encoding.Default))
                {
                    return(sr.ReadToEnd().Trim());
                }
            }
        }
        internal AutoWebProxyScriptEngine(WebProxy proxy, bool useRegistry)
        {
            GlobalLog.Assert(proxy != null, "'proxy' must be assigned.");
            webProxy = proxy;
            m_UseRegistry = useRegistry;

#if !FEATURE_PAL
            m_AutoDetector = AutoDetector.CurrentAutoDetector;
            m_NetworkChangeStatus = m_AutoDetector.NetworkChangeStatus;

            SafeRegistryHandle.RegOpenCurrentUser(UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out hkcu);
            if (m_UseRegistry)
            {
                ListenForRegistry();

                // Keep track of the identity we used to read the registry, in case we need to read it again later.
                m_Identity = WindowsIdentity.GetCurrent();
            }

#endif // !FEATURE_PAL

            // In Win2003 winhttp added a Windows Service handling the auto-proxy discovery. In XP using winhttp
            // APIs will load, compile and execute the wpad file in-process. This will also load COM, since
            // WinHttp requires COM to compile the file. For these reasons, we don't use WinHttp on XP, but
            // only on newer OS versions where the "WinHTTP Web Proxy Auto-Discovery Service" exists.
            webProxyFinder = new HybridWebProxyFinder(this);
        }
        /// <summary>
        /// アクセストークンを取得
        /// </summary>
        /// <returns></returns>
        private async Task <string> FetchTokenAsync()
        {
            // プロキシ設定
            var ch = new HttpClientHandler()
            {
                UseCookies = true
            };

            if (!string.IsNullOrEmpty(this.ProxyServer))
            {
                var proxy = new System.Net.WebProxy(this.ProxyServer);
                if (!string.IsNullOrEmpty(this.ProxyId) && !string.IsNullOrEmpty(this.ProxyPassword))
                {
                    proxy.Credentials = new System.Net.NetworkCredential(this.ProxyId, this.ProxyPassword);
                }
                ch.Proxy = proxy;
            }
            else
            {
                ch.Proxy = null;
            }

            // 認証呼び出し
            using (var client = new HttpClient(ch))
            {
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", this.APIKey);
                UriBuilder uriBuilder = new UriBuilder(this.TokenUrl);

                var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, null).ConfigureAwait(false);

                return(await result.Content.ReadAsStringAsync().ConfigureAwait(false));
            }
        }
示例#5
0
        public static WebProxy Create(string proxyName, int proxyPort, bool bypassLocal)
        {
            WebProxy proxy = new System.Net.WebProxy(proxyName, proxyPort);

            proxy.BypassProxyOnLocal = bypassLocal;
            return(proxy);
        }
示例#6
0
        /// <summary>
        /// Sets the default proxy for every HTTP request.
        /// If the caller would like to know if the call throws any exception, the second parameter should be set to true
        /// </summary>
        /// <param name="settings">proxy settings.</param>
        /// <param name="throwExceptions">If set to <c>true</c> throw exceptions.</param>
        public static void SetDefaultProxy(Config.ProxySettings settings, bool throwExceptions = false)
        {
            try
            {
                IWebProxy proxy = null;
                switch(settings.Selection) {
                    case Config.ProxySelection.SYSTEM:
                        proxy = WebRequest.GetSystemWebProxy();
                        break;
                    case Config.ProxySelection.CUSTOM:
                        proxy = new WebProxy(settings.Server);
                        break;
                }

                if (settings.LoginRequired && proxy != null) {
                    proxy.Credentials = new NetworkCredential(settings.Username, Crypto.Deobfuscate(settings.ObfuscatedPassword));
                }

                WebRequest.DefaultWebProxy = proxy;
            }
            catch (Exception e)
            {
                if (throwExceptions) {
                    throw;
                }

                Logger.Warn("Failed to set the default proxy, please check your proxy config: ", e);
            }
        }
示例#7
0
        public XmlRpcPings(string name, string url, string feedUrl, string[] pingUrls)
        {
            this.siteName = name;
            this.siteUrl = url;
            this.siteFeedUrl = feedUrl;
            this.pingServiceUrls = pingUrls;

            this.UserAgent = SiteSettings.VersionDescription;
            this.Timeout = 60000;

            // This improves compatibility with XML-RPC servers that do not fully comply with the XML-RPC specification.
            this.NonStandard = XmlRpcNonStandard.All;

            // Use a proxy server if one has been configured
            SiteSettings siteSettings = SiteSettings.Get();
            if (siteSettings.ProxyHost != string.Empty)
            {
                WebProxy proxy = new WebProxy(siteSettings.ProxyHost, siteSettings.ProxyPort);
                proxy.BypassProxyOnLocal = siteSettings.ProxyBypassOnLocal;

                if (siteSettings.ProxyUsername != string.Empty)
                    proxy.Credentials = new NetworkCredential(siteSettings.ProxyUsername, siteSettings.ProxyPassword);

                this.Proxy = proxy;
            }
        }
 public BetfairClientSync(Exchange exchange,
     string appKey,
     Action preNetworkRequest = null,
     WebProxy proxy = null)
 {
     client = new BetfairClient(exchange, appKey, preNetworkRequest, proxy);
 }
示例#9
0
        public static bool Get_Launch_Specific_Data(out String user_data)
        {
            user_data = String.Empty;
            try
            {
                string sURL = "http://169.254.169.254/latest/user-data/";
                WebRequest wrGETURL;
                wrGETURL = WebRequest.Create(sURL);
                WebProxy myProxy = new WebProxy("myproxy", 80);
                myProxy.BypassProxyOnLocal = true;

                Stream objStream;
                objStream = wrGETURL.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(objStream);
                user_data = sr.ReadToEnd();

                Console.WriteLine("user_Data_String=" + user_data);
                if (!Get_My_IP_AND_DNS(out UtilsDLL.AWS_Utils.aws_ip, out UtilsDLL.AWS_Utils.aws_dns))
                {
                    Console.WriteLine("Get_My_IP_AND_DNS() failed!!");
                    return false;
                }
                is_aws = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Excpetion in Get_Launch_Specific_Data(). = " + e.Message);
                is_aws = false;
                return false;
            }

            return true;
        }
示例#10
0
        public static string SendRequestByPost(string serviceUrl, string postData, System.Net.WebProxy proxy, int timeout)
        {
            WebResponse objResp;
            WebRequest  objReq;
            string      strResp = string.Empty;

            byte[] byteReq;

            try {
                byteReq              = Encoding.UTF8.GetBytes(postData);
                objReq               = WebRequest.Create(serviceUrl);
                objReq.Method        = "POST";
                objReq.ContentLength = byteReq.Length;
                objReq.ContentType   = "application/x-www-form-urlencoded";
                objReq.Timeout       = timeout;
                if (proxy != null)
                {
                    objReq.Proxy = proxy;
                }
                Stream OutStream = objReq.GetRequestStream();
                OutStream.Write(byteReq, 0, byteReq.Length);
                OutStream.Close();
                objResp = objReq.GetResponse();
                StreamReader sr = new StreamReader(objResp.GetResponseStream(), Encoding.UTF8, true);
                strResp += sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception ex) {
                throw new ArgumentException("Error SendRequest: " + ex.Message + " " + ex.Source);
            }

            return(strResp);
        }
示例#11
0
        public Worker(HttpListenerContext context)
        {
            this.context = context;

            port = ConfigurationManager.AppSettings["proxy_port"];
            host = ConfigurationManager.AppSettings["proxy_host"];

            //init proxy
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["parent_host"]) && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["parent_port"]))
            {
                parent = new WebProxy(ConfigurationManager.AppSettings["parent_host"], int.Parse(ConfigurationManager.AppSettings["parent_port"]));

                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["parent_user"]))
                {
                    parent.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["parent_user"], ConfigurationManager.AppSettings["parent_pass"], ConfigurationManager.AppSettings["parent_domain"]);
                }
                else
                {
                    parent.UseDefaultCredentials = true;
                }
            }
            else
            {
                parent = null;
            }
        }
示例#12
0
        private void buttonTestPorxy_Click(object sender, EventArgs e)
        {
            if (checkBoxDontUseProxy.Checked)
            {
                SaveProxyParams();
                return;
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
            request.Credentials = new NetworkCredential(textBoxUserProxy.Text, textBoxPasswordProxy.Text);

            WebProxy webProxy = new WebProxy(textBoxURLProxy.Text, true)
            {
                UseDefaultCredentials = false
            };
            webProxy.Credentials = request.Credentials;

            request.Proxy = webProxy;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message, "Proxy authentification", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            SaveProxyParams();
            MessageBox.Show("Proxy authentification succesful", "Proxy authentification", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        public static HttpWebRequest CreateHttpWebRequest(string url, int timeoutRequestSeconds)
        {
            IInternetSettings settings = Plugin.Instance.Application.SystemPreferences.InternetSettings;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = timeoutRequestSeconds * 1000;
            if (System.Environment.OSVersion.Platform != System.PlatformID.Unix)
            {
                request.Credentials = CredentialCache.DefaultCredentials;
            }
            if (settings.UseProxy)
            {
                WebProxy proxy = new WebProxy(settings.ProxyHost, settings.ProxyPort);
                if (settings.ProxyUsername.Length > 0 && settings.ProxyPassword.Length > 0)
                {
                    proxy.Credentials = new NetworkCredential(settings.ProxyUsername, settings.ProxyPassword);
                }
                request.Proxy = proxy;
            }
            else
            {
                request.Proxy = HttpWebRequest.DefaultWebProxy;
            }
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322) ";
            return request;
        }
        public async Task GetCredentialsAsync_PassesAllParametersToProviders()
        {
            IEnumerable <ICredentialProvider> providers = new[] { _mockProvider.Object };
            // Arrange
            var service = new CredentialService(
                new AsyncLazy <IEnumerable <ICredentialProvider> >(() => Task.FromResult(providers)),
                nonInteractive: true,
                handlesDefaultCredentials: true);
            var webProxy = new WebProxy();
            var uri      = new Uri("http://uri");

            // Act
            await service.GetCredentialsAsync(
                uri,
                webProxy,
                CredentialRequestType.Proxy,
                message : "A",
                cancellationToken : CancellationToken.None);

            // Assert
            _mockProvider.Verify(x => x.GetAsync(
                                     uri,
                                     webProxy,
                                     /*type*/ CredentialRequestType.Proxy,
                                     /*message*/ "A",
                                     /*isRetry*/ It.IsAny <bool>(),
                                     /*nonInteractive*/ true,
                                     CancellationToken.None));
        }
 public HttpRequestProxy(string host, int port, string username, string password)
 {
     this.WebProxy = new System.Net.WebProxy(host, port)
     {
         Credentials = new NetworkCredential(username, password)
     };
 }
示例#16
0
        static Submit()
        {
            _key           = Config.Key.Trim();
            _input_charset = Config.Input_charset.Trim().ToLower();
            _sign_type     = Config.Sign_type.Trim().ToUpper();

            if (ConfigurationManager.AppSettings["UseProxy"] != null)
            {
                if (ConfigurationManager.AppSettings["UseProxy"].ToString() == "1")
                {
                    string strDomain = ConfigurationManager.AppSettings["Domain"].ToString();
                    //域访问名
                    string strUserName = ConfigurationManager.AppSettings["UserName"].ToString();
                    //域访问密码
                    string strPassWord = ConfigurationManager.AppSettings["PassWord"].ToString();
                    //代理地址
                    string strHost = ConfigurationManager.AppSettings["Host"].ToString();
                    //代理端口
                    int strPort = Convert.ToInt32(ConfigurationManager.AppSettings["Port"].ToString());
                    //设置代理
                    System.Net.WebProxy oWebProxy = new System.Net.WebProxy(strHost, strPort);

                    // 获取或设置提交给代理服务器进行身份验证的凭据
                    oWebProxy.Credentials = new System.Net.NetworkCredential(strUserName, strPassWord, strDomain);

                    // oWebProxy.Credentials=new  System.Net.NetworkCredential(
                    proxy = oWebProxy;
                }
            }
        }
示例#17
0
 public KeePassQiniu.KeePassQiniuExt.UploadError UploadLocal(string name, string dbfile, out string tips) {
     Init();
     System.Net.IWebProxy webProxy = null;
     if(KeePassQiniu.KeePassQiniuConfig.Default.UseProxy) {
         webProxy = new System.Net.WebProxy(KeePassQiniu.KeePassQiniuConfig.Default.ProxyUrl, true);
     }
     // bak first
     if(KeePassQiniu.KeePassQiniuConfig.Default.AutoBackup) {
         MyRSClient moveclient = new MyRSClient();
         CallRet moveret = moveclient.Move(new EntryPathPair(KeePassQiniu.KeePassQiniuConfig.Default.QiniuBucket, name, "backup_" + System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + "_" + name));
         if(!moveret.OK) {
             tips = moveret.Response;
             return KeePassQiniuExt.UploadError.AUTOBAK_ERROR;
         }
     }
     // upload
     var policy = new PutPolicy(KeePassQiniu.KeePassQiniuConfig.Default.QiniuBucket);
     string upToken = policy.Token();
     PutExtra extra = new PutExtra();
     IOClient client = new IOClient();
     client.Proxy = webProxy;
     PutRet uploadret = client.PutFile(upToken, name, dbfile, extra);
     if(!uploadret.OK) {
         tips = uploadret.Response;
         return KeePassQiniuExt.UploadError.UPLOAD_ERROR;
     }
     tips = string.Empty;
     return KeePassQiniuExt.UploadError.OK;
 }
示例#18
0
        public static string Post(string url, string reference, Char[] postDataStr/*String postDataStr*/, CookieContainer myCookieContainer, bool autoRedirect, WebProxy proxy = null)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (proxy != null)
                    request.Proxy = proxy;
                request.Method = "POST";
                request.CookieContainer = myCookieContainer;
                request.AllowAutoRedirect = autoRedirect;
                request.ContentType = "application/x-www-form-urlencoded"; //必须要的
                request.ServicePoint.Expect100Continue = false;
                if (reference != "")
                    request.Referer = reference;

                //request.ContentLength = postDataStr.Length;
                StreamWriter writer = new StreamWriter(request.GetRequestStream());
                writer.Write(postDataStr, 0, postDataStr.Length);
                writer.Flush();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));
                string retStr = sr.ReadToEnd();
                sr.Close();
                return retStr;
            }
            catch (WebException ex)
            {
                return "ERROR!:"+ ex.Message.ToString();
            }
        }
示例#19
0
        public static bool Check(string value)
        {
            var myProxy = new WebProxy();
            myProxy.Address = new Uri("http://proxy.ftc.ru:3128");
            myProxy.Credentials = new NetworkCredential("pogoda", "Fle17qHx0");

            var req = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=6LculQwTAAAAAMGQKfIG6-iC3tPqeoZgNiRj31T6&response=" + value);
            req.Proxy = myProxy;
            var Valid = false;

            try
            {
                using(var wResponse = req.GetResponse())
                {
                    using (var readStream = new StreamReader(wResponse.GetResponseStream()))
                    {
                        var jsonResponse = readStream.ReadToEnd();

                        var js = new JavaScriptSerializer();
                        var data = js.Deserialize<RecatchResponse>(jsonResponse);

                        Valid = Convert.ToBoolean(data.Success);
                    }
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }

            return Valid;
        }
示例#20
0
        public static string SendRequestByGet(string serviceUrl, System.Net.WebProxy proxy, int timeout)
        {
            WebResponse objResp;
            WebRequest  objReq;
            string      strResp = string.Empty;

            try
            {
                objReq         = WebRequest.Create(serviceUrl);
                objReq.Method  = "GET";
                objReq.Timeout = timeout;
                if (proxy != null)
                {
                    objReq.Proxy = proxy;
                }
                objResp = objReq.GetResponse();
                StreamReader sr = new StreamReader(objResp.GetResponseStream(), Encoding.UTF8, true);
                strResp += sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Error SendRequest: " + ex.Message + " " + ex.Source);
            }

            return(strResp);
        }
示例#21
0
        private ClientContext CreateContext()
        {
            ClientContext clientContext = new ClientContext(new Uri(_serverSettings.Uri));
             if (_serverSettings.UserName != null)
             {
            clientContext.Credentials = new NetworkCredential(_serverSettings.UserName, _serverSettings.Password, _serverSettings.Domain);
             }

             if (_serverSettings.ProxyUri != null)
             {
            System.Net.WebProxy proxy = new System.Net.WebProxy(_serverSettings.ProxyUri, _serverSettings.ProxyPort);
            if (proxy.Credentials == null && clientContext.Credentials != null)
            {
               proxy.Credentials = clientContext.Credentials;
            }
            else
            {
               proxy.Credentials = CredentialCache.DefaultCredentials;
            }

            WebRequest.DefaultWebProxy = proxy;
             }
             else
            WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy(); // Get default system proxy settings

             return clientContext;
        }
示例#22
0
        private static System.Net.WebProxy GetProxy()
        {
            System.Net.WebProxy webProxy = null;
            //try
            //{
            //    // 代理链接地址加端口
            //    string proxyHost = "192.168.1.1";
            //    string proxyPort = "9030";

            //    // 代理身份验证的帐号跟密码
            //    //string proxyUser = "******";
            //    //string proxyPass = "******";

            //    // 设置代理服务器
            //    webProxy = new System.Net.WebProxy();
            //    // 设置代理地址加端口
            //    webProxy.Address = new Uri(string.Format("{0}:{1}", proxyHost, proxyPort));
            //    // 如果只是设置代理IP加端口,例如192.168.1.1:80,这里直接注释该段代码,则不需要设置提交给代理服务器进行身份验证的帐号跟密码。
            //    //webProxy.Credentials = new System.Net.NetworkCredential(proxyUser, proxyPass);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("获取代理信息异常", DateTime.Now.ToString(), ex.Message);
            //}
            return(webProxy);
        }
        /// <summary>
        /// Create a web request.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public HttpWebRequest Create(Uri uri, string contentType) {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            if (settings.HasProxySettings) {
                NetworkCredential credentials = null;
                if (settings.HasProxyCredentials) {
                    if (!string.IsNullOrWhiteSpace(settings.ProxyDomain)) {
                        credentials = new NetworkCredential(settings.ProxyUserName, settings.ProxyPassword, settings.ProxyDomain);
                    }
                    else {
                        credentials = new NetworkCredential(settings.ProxyUserName, settings.ProxyPassword);
                    }
                }

                WebProxy proxy = null;
                if (credentials != null) {
                    proxy = new WebProxy(settings.ProxyUrl, settings.BypassProxyOnLocal, null, credentials);
                }
                else {
                    proxy = new WebProxy(settings.ProxyUrl, settings.BypassProxyOnLocal);
                }
                request.Proxy = proxy;
            }
            request.Timeout = settings.TimeoutInSeconds * 1000;
            if (contentType != null && contentType.IndexOf(";") > 0) {
                request.ContentType = contentType.Substring(0, contentType.IndexOf(";"));
            }
            else {
                request.ContentType = contentType;
            }
            request.Method = "POST";

            return request;
        }
        /// <summary>
        /// Send a GET request to a web page. Returns the contents of the page.
        /// </summary>
        /// <param name="url">The address to GET.</param>
        public string Get(string url, ProxySettings settings)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            // Use a proxy
            if (settings.UseProxy)
            {
                IWebProxy proxy = request.Proxy;
                WebProxy myProxy = new WebProxy();
                Uri newUri = new Uri(settings.ProxyAddress);

                myProxy.Address = newUri;
                myProxy.Credentials = new NetworkCredential(settings.ProxyUsername, settings.ProxyPassword);
                request.Proxy = myProxy;
            }

            request.Method = "GET";
            request.CookieContainer = cookies;
            WebResponse response = request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            string result = sr.ReadToEnd();
            sr.Close();
            response.Close();

            return result;
        }
 public Account(string userName, string password, string proxyIp)
 {
     this.Username = userName;
     this.Password = password;
     if(!string.IsNullOrEmpty(proxyIp))
     Proxy = new WebProxy(proxyIp,443); //https����
 }
示例#26
0
        public static XmlDocument GetXmlFromUrl(string url, WebProxy proxy)
        {
            XmlDocument xmldoc = new XmlDocument();

            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            if (proxy != null) request.Proxy = proxy;

            request.Timeout = 15 * 1000;

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                xmldoc.LoadXml(reader.ReadToEnd());
                reader.Close();
            }
            else
            {
                xmldoc = null;
                throw new Exception(response.StatusCode.ToString());
            }

            return xmldoc;
        }
        public static void SetDefaultProxy(this HttpWebRequest request)
        {
            if (request != null)
            {
                // Get the config for the proxy
                bool proxyActive = false;
                bool.TryParse(WebConfigurationManager.AppSettings["Proxy.Active"], out proxyActive);

                // No need to process the rest if there is no proxy
                if (proxyActive)
                {
                    string proxyUrl = WebConfigurationManager.AppSettings["Proxy.Url"];
                    int proxyPort = 80;
                    int.TryParse(WebConfigurationManager.AppSettings["Proxy.Port"], out proxyPort);
                    string proxyUser = WebConfigurationManager.AppSettings["Proxy.Username"];
                    string proxyPassword = WebConfigurationManager.AppSettings["Proxy.Password"];
                    string proxyDomain = WebConfigurationManager.AppSettings["Proxy.Domain"];

                    WebProxy proxy = new WebProxy(proxyUrl, proxyPort);
                    if (!string.IsNullOrEmpty(proxyUser) || !string.IsNullOrEmpty(proxyPassword) || !string.IsNullOrEmpty(proxyDomain))
                        proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword, proxyDomain);

                    request.Proxy = proxy;
                }
            }
        }
示例#28
0
        public static string GetToken(string url, WebProxy proxy = null)
        {
            string webData = WebCache.Instance.GetWebData(@"http://ida.omroep.nl/npoplayer/i.js?s=" + HttpUtility.UrlEncode(url), proxy: proxy);
            string result = String.Empty;

            Match m = Regex.Match(webData, @"token\s*=\s*""(?<token>[^""]*)""");
            if (m.Success)
            {
                int first = -1;
                int second = -1;
                string token = m.Groups["token"].Value;
                for (int i = 5; i < token.Length - 4; i++)
                    if (Char.IsDigit(token[i]))
                    {
                        if (first == -1)
                            first = i;
                        else
                            if (second == -1)
                                second = i;
                    }
                if (first == -1) first = 12;
                if (second == -1) second = 13;
                char[] newToken = token.ToCharArray();
                newToken[first] = token[second];
                newToken[second] = token[first];
                return new String(newToken);
            }
            return null;
        }
        public async Task GetCredentials_PassesAllParametersToProviders()
        {
            // Arrange
            var service = new CredentialService(
                new[] { _mockProvider.Object },
                TestableErrorWriter,
                nonInteractive: true);
            var webProxy = new WebProxy();
            var uri      = new Uri("http://uri");

            // Act
            await service.GetCredentialsAsync(
                uri,
                webProxy,
                CredentialRequestType.Proxy,
                message : "A",
                cancellationToken : CancellationToken.None);

            // Assert
            _mockProvider.Verify(x => x.GetAsync(
                                     uri,
                                     webProxy,
                                     /*type*/ CredentialRequestType.Proxy,
                                     /*message*/ "A",
                                     /*isRetry*/ It.IsAny <bool>(),
                                     /*nonInteractive*/ true,
                                     CancellationToken.None));
        }
        public IWebProxy GetProxy()
        {
            IWebProxy proxy = null;
            if (Settings != null) {
                if (Settings.IsEnabled) {
                    if ((ProxyMode)Settings.Mode != ProxyMode.Default && string.IsNullOrEmpty(Settings.Host)) {
                        return null;
                    }
                    switch ((ProxyMode)Settings.Mode) {
                        case ProxyMode.Default:
                            proxy = WebRequest.GetSystemWebProxy();
                            break;

                        case ProxyMode.HTTP:
                            proxy = new WebProxy(string.Format("http://{0}:{1}/", Settings.Host, Settings.Port), true);
                            break;

                        case ProxyMode.HTTPS:
                            proxy = new WebProxy(Settings.Host, Settings.Port);
                            break;
                    }
                    if ((ProxyMode)Settings.Mode != ProxyMode.Default &&
                        Settings.Authentication && Settings.Credentials.IsCorrect) {
                        proxy.Credentials = new NetworkCredential(Settings.Credentials.User, Settings.Credentials.SecurePassword);
                    }
                }
            } else {
                proxy = WebRequest.GetSystemWebProxy();
            }
            return proxy;
        }
示例#31
0
        /// <summary>
        /// Computes a <see cref="IWebProxy">web proxy</see> resolver instance
        /// based on the combination of proxy-related settings in this vault
        /// configuration.
        /// </summary>
        /// <returns></returns>
        public IWebProxy GetWebProxy()
        {
            IWebProxy wp = null;

            if (UseNoProxy)
            {
                wp = GlobalProxySelection.GetEmptyWebProxy();
            }
            else if (!string.IsNullOrEmpty(ProxyUri))
            {
                var newwp = new WebProxy(ProxyUri);
                if (UseDefCred)
                {
                    newwp.UseDefaultCredentials = true;
                }
                else if (!string.IsNullOrEmpty(Username))
                {
                    var pw = PasswordEncoded;
                    if (!string.IsNullOrEmpty(pw))
                        pw = Encoding.Unicode.GetString(Convert.FromBase64String(pw));
                    newwp.Credentials = new NetworkCredential(Username, pw);
                }
            }

            return wp;
        }
示例#32
0
        public bool Login(string address, string user, string pass, WebProxy proxy)
        {
            //Separate HTTPMethod from ApiCall
            var split = LoginAPI.Split(new[] { "|||" }, StringSplitOptions.None);
            var api = split[0];
            var loginUri = Prefix + address + api;

            var s = new StringBuilder();
            s.Append("{ \"name\":\"");
            s.Append(user);
            s.Append("\", \"password\": \"");
            s.Append(pass);
            s.Append("\"}");

            var status = Convert.ToString(Execute(loginUri, s.ToString(), "POST", proxy));

            switch (status)
            {
                case "":
                    return true;

                default:
                    return false;
            }
        }
示例#33
0
 public static String TryGetHTMLString(String username, String password, String code
     , WebProxy proxy, bool isNormal)
 {
     String resultStr = null;
     int maxTry = 3;
     while (resultStr == null && maxTry-- > 0)
     {
         try
         {
             if (isNormal)
             {
                 resultStr = GetHTMLString(username, password, code, proxy);
             }
             else
             {
                 Assembly asm = Assembly.Load("GPAToolPro");
                 Type util = asm.GetType("GPAToolPro.AdminFunctionLib");
                 Object result = util.InvokeMember("GetAdminScoreHTMLString", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod
                     , null, null, new object[] { username, XMLConfig.adminUsername, XMLConfig.adminPassword, code, proxy });
                 resultStr = (result == null && result is String) ? null : (String)result;
             }
         }
         catch
         {
             resultStr = null;
         }
     }
     return resultStr;
 }
示例#34
0
        public string POST(string url, string query)
        {
            HttpWebRequest hwrq = CreateRequest(url);

            hwrq.CookieContainer = Cookies;
            hwrq.Method          = "POST";
            Decryptor decryptor = new Decryptor("ckuJ1YQrX7ysO/WVHkowGA==");

            hwrq.Credentials            = new NetworkCredential("d.astahov", decryptor.DescryptStr, "GRADIENT");
            hwrq.ContentType            = "application/x-www-form-urlencoded";
            hwrq.AutomaticDecompression = DecompressionMethods.GZip;
            WebProxy proxy = new System.Net.WebProxy("proxy-dc.gradient.ru", 3128);

            proxy.Credentials = hwrq.Credentials;
            hwrq.Proxy        = proxy;


            byte[] data = Encoding.UTF8.GetBytes(query);
            hwrq.ContentLength = data.Length;
            hwrq.GetRequestStream().Write(data, 0, data.Length);
            using (HttpWebResponse hwrs = (HttpWebResponse)hwrq.GetResponse())
            {
                Cookies.Add(hwrs.Cookies);
                using (StreamReader sr = new StreamReader(hwrs.GetResponseStream(), Encoding.Default))
                {
                    return(sr.ReadToEnd().Trim());
                }
            }
        }
示例#35
0
        public void ProxySet()
        {
            if (CustomProxy.Checked && !string.IsNullOrEmpty(Address.Text))
            {
                try
                {
                    System.Net.WebProxy myProxy = new System.Net.WebProxy(Address.Text);
                    if (!string.IsNullOrEmpty(Port.Text))
                    {
                        myProxy = new System.Net.WebProxy(Address.Text, Convert.ToInt16(Port.Text));
                    }
                    myProxy.BypassProxyOnLocal    = true;
                    myProxy.UseDefaultCredentials = true;

                    if (Authorization.Checked)
                    {
                        myProxy.Credentials = new System.Net.NetworkCredential(UserName.Text, Password.Text);
                    }
                    WebRequest.DefaultWebProxy = myProxy;
                }
                catch (Exception ex)
                {
                    ErrorHandler.Handle(ex);
                }
            }
            else // to do set defaul system proxy
            {
                WebRequest.DefaultWebProxy = _systemProxy;
            }
        }
示例#36
0
        public List<Result> Request(string url, WebProxy proxy)
        {
            WebClient webClient = new WebClient();
              webClient.Proxy     = proxy;

              webClient.QueryString.Add("db",          "999");
              webClient.QueryString.Add("output_type", "2");
              webClient.QueryString.Add("numres",      "16");
              webClient.QueryString.Add("api_key",     ApiKey);
              webClient.QueryString.Add("url",         url);

              List<Result> results = new List<Result>();

              try {
            string  response = webClient.DownloadString(ENDPOINT);
            dynamic dynObj   = JsonConvert.DeserializeObject(response);
            foreach(var result in dynObj.results) {
              results.Add(new Result(result.header, result.data));
            }
              }
              catch (Exception e) {
            Console.WriteLine(e.Message);
              }

              return results;
        }
示例#37
0
        void CheckForUpdates()
        {
            if (task == null || task.Status != TaskStatus.Running)
            {
                var container = TinyIoCContainer.Current;

                IResourceProvider resource = container.Resolve <IResourceProvider>(ContainerNSR.RESOURCE_PROVIDER);

                IConfigProvider config = container.Resolve <IConfigProvider>(ContainerNSR.APP_SETTINGS);

                ServiceUpdater updater = new ServiceUpdater();

                IWebProxy proxy = null;

                if (config.EnableProxy)
                {
                    proxy = new System.Net.WebProxy(config.Host, config.Port);
                    if (config.EnableCredentials)
                    {
                        proxy.Credentials = new System.Net.NetworkCredential(config.User, config.Password, config.Domain);
                    }
                }

                System.Version currentVersion = Utility.GetVersionInfo(this.GetType().Assembly);

                task = Task.Factory.StartNew(() => {
                    ServiceUpdater.VersionInfo version = updater.GetMetaInfoVersion(resource.VersionCheckUri.ToString());

                    return(version);
                }).ContinueWith((o) => {
                    if (o.Status != TaskStatus.Faulted)
                    {
                        System.Version latestVersion = o.Result.LatestVersion;

                        bool isVersionUpToDate = latestVersion <= currentVersion;

                        VersionCheckEventArgs eventArgs = new VersionCheckEventArgs {
                            Version = latestVersion
                        };

                        if (isVersionUpToDate == false)
                        {
                            OnNewVersionFoundEvent(this, eventArgs);
                        }
                        else
                        {
                            OnVersionUpToDateEvent(this, eventArgs);
                        }
                    }
                    else
                    {
                        VersionCheckEventArgs eventArgs = new VersionCheckEventArgs {
                            ErrorMessage = o.Exception.Message
                        };

                        OnNetworkErrorEvent(this, eventArgs);
                    }
                });
            }
        }
示例#38
0
        public void Refresh()
        {
            if (Configuration == ProxyConfiguration.None)
                Proxy = null;

            else if (Configuration == ProxyConfiguration.System)
            {
                //quick hack since WebProxy.GetDefaultProxy is deprecated
                var address = WebRequest.DefaultWebProxy.GetProxy(new Uri("http://www.google.com"));
                Proxy = new WebProxy(address) {UseDefaultCredentials = true};
            }

            else if (Configuration == ProxyConfiguration.Manual)
            {
                if (ManualProxyParameters == null)
                    throw new ProxyConfigurationException("Manual proxy parameters are not set.");

                Proxy = new WebProxy(ManualProxyParameters.Host, ManualProxyParameters.Port)
                {
                    UseDefaultCredentials = false
                };

                if (ManualProxyParameters.Credentials != null)
                    Proxy.Credentials = ManualProxyParameters.Credentials;
            }
        }
		public static InstallerService GetInstallerWebService()
		{
			var webService = new InstallerService();

			string url = AppConfigManager.AppConfiguration.GetStringSetting(ConfigKeys.Web_Service);
			if (!String.IsNullOrEmpty(url))
			{
				webService.Url = url;
			}
			else
			{
				webService.Url = "http://www.websitepanel.net/Services/InstallerService-2.1.asmx";
			}

			// check if we need to add a proxy to access Internet
			bool useProxy = AppConfigManager.AppConfiguration.GetBooleanSetting(ConfigKeys.Web_Proxy_UseProxy);
			if (useProxy)
			{
				string proxyServer = AppConfigManager.AppConfiguration.Settings[ConfigKeys.Web_Proxy_Address].Value;
				if (!String.IsNullOrEmpty(proxyServer))
				{
					IWebProxy proxy = new WebProxy(proxyServer);
					string proxyUsername = AppConfigManager.AppConfiguration.Settings[ConfigKeys.Web_Proxy_UserName].Value;
					string proxyPassword = AppConfigManager.AppConfiguration.Settings[ConfigKeys.Web_Proxy_Password].Value;
					if (!String.IsNullOrEmpty(proxyUsername))
						proxy.Credentials = new NetworkCredential(proxyUsername, proxyPassword);
					webService.Proxy = proxy;
				}
			}

			return webService;
		}
示例#40
0
        public static byte[] GetBytesFromUrl(string url, WebProxy proxy) 
		{
			byte[] bytes = null;

			HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            if (proxy != null)  request.Proxy = proxy;
            
			request.Timeout = 15 * 1000;

			HttpWebResponse response = request.GetResponse() as HttpWebResponse;

			if (response.StatusCode == HttpStatusCode.OK) 
			{
				BinaryReader reader = new BinaryReader(response.GetResponseStream());				
				bytes = reader.ReadBytes(Convert.ToInt32(response.ContentLength));
				reader.Close();
				reader = null;
			}
			else 
			{
				throw new Exception(response.StatusCode.ToString());
			}

			return bytes;
		}
示例#41
0
        public static string SendRequestByPost(string serviceUrl, string postData, System.Net.WebProxy proxy, int timeout)
        {
            WebResponse resp     = null;
            WebRequest  req      = null;
            string      response = string.Empty;

            byte[] reqBytes = null;

            try
            {
                reqBytes          = Encoding.UTF8.GetBytes(postData);
                req               = WebRequest.Create(serviceUrl);
                req.Method        = "POST";
                req.ContentLength = reqBytes.Length;
                req.ContentType   = "application/x-www-form-urlencoded";
                req.Timeout       = timeout;
                if (proxy != null)
                {
                    req.Proxy = proxy;
                }
                Stream outStream = req.GetRequestStream();
                outStream.Write(reqBytes, 0, reqBytes.Length);
                outStream.Close();
                resp = req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8, true);
                response += sr.ReadToEnd();
                sr.Close();
            }
            catch
            {
                throw;
            }

            return(response);
        }
示例#42
0
        public TwitterSearchStream(TwitterProtocolManager protocolManager,
                                   GroupChatModel chat, string keyword,
                                   OAuthTokens tokens, WebProxy proxy)
        {
            if (protocolManager == null) {
                throw new ArgumentNullException("protocolManager");
            }
            if (chat == null) {
                throw new ArgumentNullException("chat");
            }
            if (keyword == null) {
                throw new ArgumentNullException("keyword");
            }
            if (tokens == null) {
                throw new ArgumentNullException("tokens");
            }

            ProtocolManager = protocolManager;
            Session = protocolManager.Session;
            Chat = chat;

            var options = new StreamOptions();
            options.Track.Add(keyword);

            Stream = new TwitterStream(tokens, null, options);
            Stream.Proxy = proxy;
            Stream.StartPublicStream(OnStreamStopped, OnStatusCreated, OnStatusDeleted, OnEvent);

            MessageRateLimiter = new RateLimiter(5, TimeSpan.FromSeconds(5));
        }
        private static void setProxyInfo(SetupConf setVariables, FtpWebRequest request)
        {
            try
            {
                string strProxyServer = setVariables.objProxyVariables.proxyServer.ToString();
                string strProxyPort = setVariables.objProxyVariables.proxyPort.ToString();
                string strProxyUsername = setVariables.objProxyVariables.proxyUsername.ToString();
                string strProxyPassword = setVariables.objProxyVariables.proxyPassword.ToString();

                IWebProxy proxy = request.Proxy;
                if (proxy != null)
                {
                    Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
                }

                WebProxy myProxy = new WebProxy();
                Uri newUri = new Uri(Uri.UriSchemeHttp + "://" + strProxyServer + ":" + strProxyPort);
                // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
                myProxy.Address = newUri;
                // Create a NetworkCredential object and associate it with the
                // Proxy property of request object.
                myProxy.Credentials = new NetworkCredential(strProxyUsername, strProxyPassword);
                request.Proxy = myProxy;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
                Console.ReadLine();
                System.Environment.Exit(-1);
            }
        }
示例#44
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.Net.NetworkCredential cr = new System.Net.NetworkCredential("moviedo", "3");
            System.Net.WebProxy          pr = new System.Net.WebProxy("127.0.1.2", 80);

            gastosWs.SingleService2 svc = new WebService_Secure.gastosWs.SingleService2();
            string list;

            svc.Credentials = cr;
            //svc.Proxy = pr;
            try
            {
                // list = svc.GetServicesList("", false);
                using (gastosWs.SingleService2 wService = new gastosWs.SingleService2())
                {
                    wService.Credentials = cr;
                    wService.Url         = "http://katy.sytes.net/gastosws/SingleService.asmx";
                    list = wService.GetServicesList("", true);
                }
                MessageBox.Show(list);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Fwk.Exceptions.ExceptionHelper.GetAllMessageException(ex));
            }
        }
示例#45
0
		public void BypassArrayList ()
		{
			Uri proxy1 = new Uri ("http://proxy.contoso.com");
			Uri proxy2 = new Uri ("http://proxy2.contoso.com");

			WebProxy p = new WebProxy (proxy1, true);
			p.BypassArrayList.Add ("http://proxy2.contoso.com");
			p.BypassArrayList.Add ("http://proxy2.contoso.com");
			Assert.AreEqual (2, p.BypassList.Length, "#1");
			Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.google.com")), "#2");
			Assert.IsTrue (p.IsBypassed (proxy2), "#3");
			Assert.AreEqual (proxy2, p.GetProxy (proxy2), "#4");

			p.BypassArrayList.Add ("?^!@#$%^&}{][");
			Assert.AreEqual (3, p.BypassList.Length, "#10");
			try {
				Assert.IsTrue (!p.IsBypassed (proxy2), "#11");
				Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.x.com")), "#12");
				Assert.AreEqual (proxy1, p.GetProxy (proxy2), "#13");
				// hmm... although #11 and #13 succeeded before (#3 resp. #4), 
				// it now fails to bypass, and the IsByPassed and GetProxy 
				// methods do not fail.. so when an illegal regular 
				// expression is added through this property it's ignored. 
				// probably an ms.net bug?? :(
			} catch (ArgumentException) {
				Assert.Fail ("#15: illegal regular expression");
			}
		}
        /// <summary>
        /// Send lottery resoult to all clients
        /// </summary>
        /// <param name="name"></param>
        /// <param name="message"></param>
        

        public void SendLotteryResult(string name, string message)
        {
            //Get lottery result
            //

            WebRequest wrGETURL;
            wrGETURL = WebRequest.Create("http://ketqua.net/widget/xo-so-mien-bac.html");

            WebProxy myProxy = new WebProxy("myproxy", 80);
            myProxy.BypassProxyOnLocal = true;

            wrGETURL.Proxy = WebProxy.GetDefaultProxy();

            Stream objStream;
            objStream = wrGETURL.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int i = 0;

            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                    Clients.All.ClientUpdateLotteryResult(name, sLine);
            }

            //Clients.All.ClientUpdateLotteryResult(name, message);
        }
示例#47
0
 /// <summary>
 /// 代理使用示例
 /// </summary>
 /// <param name="Url"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public static string GetUrltoHtml(string Url, string type = "UTF-8")
 {
     try
     {
         var request = (HttpWebRequest)WebRequest.Create(Url);
         request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
         WebProxy myProxy = new WebProxy("192.168.15.11", 8015);
         //建议连接(代理需要身份认证,才需要用户名密码)
         myProxy.Credentials = new NetworkCredential("admin", "123456");
         //设置请求使用代理信息
         request.Proxy = myProxy;
         // Get the response instance.
         System.Net.WebResponse wResp = request.GetResponse();
         System.IO.Stream respStream = wResp.GetResponseStream();
         // Dim reader As StreamReader = New StreamReader(respStream)
         using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
         {
             return reader.ReadToEnd();
         }
     }
     catch (Exception)
     {
         //errorMsg = ex.Message;
     }
     return "";
 }
示例#48
0
        static void Main(string[] args)
        {
            try
            {
                //ライセンスサーバのURL
                string httpURL = "https://license.qlikcloud.com/";
                //defaultのプロキシ設定を使用しない
                WebRequest.DefaultWebProxy = null;
                //HHTPリクエスト
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(httpURL);
                //タイムアウト設定(5秒)
                req.Timeout = 5000;
                //プロキシサーバの入力
                Console.WriteLine("プロキシサーバのURLを[http://<プロキシーサーバー>:ポート番号]の形式で入力して下さい。");
                Console.WriteLine("プロキシサーバを使用しない場合はEnterを押して下さい");

                //標準入の情報を受取
                string ProxyURL = Console.ReadLine();

                if (ProxyURL != "")
                {
                    //プロキシ設定
                    WebProxy proxy = new System.Net.WebProxy(ProxyURL);
                    req.Proxy = proxy;
                }

                //HTTPサーバからデータを受け取る
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            }
            catch (System.Net.WebException ex)
            {
                Console.WriteLine("\r\n<応答結果>");
                //HTTPプロトコルエラーかどうか調べる
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    //HttpWebResponseを取得
                    HttpWebResponse errres = (System.Net.HttpWebResponse)ex.Response;
                    //応答したURIを表示する
                    Console.WriteLine("URI: " + errres.ResponseUri);
                    //応答ステータスコードを表示する
                    Console.WriteLine("ステータスコード: " + errres.StatusCode);

                    if (errres.ResponseUri.ToString() == "https://license.qlikcloud.com/" && errres.StatusCode.ToString() == "NotFound")
                    {
                        Console.WriteLine("\r\n疎通OK");
                    }
                    else
                    {
                        Console.WriteLine("\r\n疎通NG");
                    }
                }
                else
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadLine();
        }
示例#49
0
        public WebProxy processProxySettings()
        {
            System.Net.WebProxy          proxy       = System.Net.WebProxy.GetDefaultProxy();
            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(proxyUser, proxyPassword, proxyDomain);
            proxy.Credentials = credentials;

            return(proxy);
        }
示例#50
0
        private SP.ClientContext GetClientContext(string webUrl)
        {
            SP.ClientContext ctx = new SP.ClientContext(webUrl);
            if (txtUser.Text != "")
            {
                string domain = "";
                string user   = "";
                if (txtUser.Text.Replace('/', '\\').Contains('\\'))
                {
                    string[] tmp = txtUser.Text.Split('\\');
                    domain = tmp[0];
                    user   = tmp[1];
                }
                else
                {
                    user = txtUser.Text;
                }
                string password = txtPwd.Text;

                if (chkLoginOnline.Checked)
                {
                    System.Security.SecureString secpwd = new System.Security.SecureString();
                    for (int i = 0; i < password.Length; i++)
                    {
                        secpwd.AppendChar(password[i]);
                    }
                    //ClientAuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
                    //FormsAuthenticationLoginInfo creds = new FormsAuthenticationLoginInfo(User, Password);
                    SharePointOnlineCredentials creds = new SharePointOnlineCredentials(user, secpwd);
                    ctx.Credentials = creds;
                }
                else
                {
                    ctx.Credentials = new System.Net.NetworkCredential(user, txtPwd.Text, domain);
                }
            }
            if (string.IsNullOrEmpty(ProxyUrl) == false)
            {
                ctx.ExecutingWebRequest += (sen, args) =>
                {
                    System.Net.WebProxy myProxy = new System.Net.WebProxy(ProxyUrl);
                    string domain = "";
                    string user   = "";
                    if (ProxyUser.Replace('/', '\\').Contains('\\'))
                    {
                        string[] tmp = ProxyUser.Split('\\');
                        domain = tmp[0];
                        user   = tmp[1];
                    }
                    // myProxy.Credentials = new System.Net.NetworkCredential(ProxyUser, ProxyPwd, domain);
                    myProxy.Credentials                      = System.Net.CredentialCache.DefaultCredentials;
                    myProxy.UseDefaultCredentials            = true;
                    args.WebRequestExecutor.WebRequest.Proxy = myProxy;
                };
            }

            return(ctx);
        }
示例#51
0
        public static string Proxy_GetRequest2(string url)
        {
            try
            {
                WebClientEx webClient = new WebClientEx();

                //webClient.Encoding = Encoding.GetEncoding("gb2312");
                if (true)
                {
                    //IP: 帐号: tets1106密码: tets1106开通成功!http端口:808
                    //创建 代理服务器设置对象 的实例
                    System.Net.WebProxy wp = new System.Net.WebProxy("123.249.2.2:888");
                    //代理服务器需要验证
                    wp.BypassProxyOnLocal = false;
                    //用户名密码
                    wp.Credentials = new NetworkCredential("te1107", "te1107");
                    ////将代理服务器设置对象赋予全局设定
                    //System.Net.GlobalProxySelection.Select = wp;



                    webClient.Proxy = wp;
                }
                webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
                Stream stream = webClient.OpenRead(url);

                StreamReader sr     = new StreamReader(stream);
                var          result = sr.ReadToEnd();

                Debug.WriteLine(url);
                return(result);
            }
            catch (IOException ioException)
            {
                throw;
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    switch (((System.Net.HttpWebResponse)(ex.Response)).StatusCode)
                    {
                    case HttpStatusCode.Unauthorized:
                        throw new UnauthorizedAccessException("UnauthorizedAccess", ex);

                    default:
                        throw;
                    }
                }
                else
                {
                    throw;
                }
            }
            finally
            {
            }
        }
 /// <summary>
 /// 设置Web代理
 /// </summary>
 /// <param name="host"></param>
 /// <param name="port"></param>
 /// <param name="username"></param>
 /// <param name="password"></param>
 public static void SetHttpProxy(string host, string port, string username, string password)
 {
     ICredentials cred;
     cred = new NetworkCredential(username, password);
     if (!string.IsNullOrEmpty(host))
     {
         _webproxy = new System.Net.WebProxy(host + ":" + port ?? "80", true, null, cred);
     }
 }
示例#53
0
        public void ObtenerTicket(string RutaCertificado, long Cuit, string Servicio)
        {
            LoginTicket objTicketRespuesta;
            string      strTicketRespuesta;

            try
            {
                //Crear WebProxy
                System.Net.WebProxy wp = null;
                //if (!System.Configuration.ConfigurationManager.AppSettings["Proxy"].ToUpper().Equals("NO"))
                //{
                //    wp = new System.Net.WebProxy(System.Configuration.ConfigurationManager.AppSettings["Proxy"], false);
                //    string usuarioProxy = System.Configuration.ConfigurationManager.AppSettings["UsuarioProxy"];
                //    string claveProxy = System.Configuration.ConfigurationManager.AppSettings["ClaveProxy"];
                //    string dominioProxy = System.Configuration.ConfigurationManager.AppSettings["DominioProxy"];

                //    System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(usuarioProxy, claveProxy, dominioProxy);
                //    wp.Credentials = networkCredential;

                //    //System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
                //    //string wsaaurl = System.Configuration.ConfigurationManager.AppSettings["ar_gov_afip_wsaa_LoginCMSService"];
                //    //credentialCache.Add(new Uri(wsaaurl), "NTLM", networkCredential);
                //    //string wsfeurl = System.Configuration.ConfigurationManager.AppSettings["ar_gov_afip_wsw_Service"];
                //    //credentialCache.Add(new Uri(wsfeurl), "NTLM", networkCredential);
                //    //wp.Credentials = credentialCache;
                //}
                //URL Login
                string urlWsaa = System.Configuration.ConfigurationManager.AppSettings["ar_gov_afip_wsaa_LoginCMSService"];
                //Obtener Ticket
                string servicio = DEFAULT_SERVICIO;
                if (Servicio != "")
                {
                    servicio = Servicio;
                }
                strTicketRespuesta                   = ObtenerLoginTicketResponse(servicio, urlWsaa, RutaCertificado, false, Wp);
                objAutorizacion                      = new ar.gov.afip.wsw.FEAuthRequest();
                objAutorizacion.Token                = Token;
                objAutorizacion.Sign                 = Sign;
                objAutorizacion.cuit                 = Cuit;
                objAutorizacionfev1                  = new ar.gov.afip.wsfev1.FEAuthRequest();
                objAutorizacionfev1.Token            = Token;
                objAutorizacionfev1.Sign             = Sign;
                objAutorizacionfev1.Cuit             = Cuit;
                objAutorizacionfexv1                 = new ar.gov.afip.wsfexv1.ClsFEXAuthRequest();
                objAutorizacionfexv1.Token           = Token;
                objAutorizacionfexv1.Sign            = Sign;
                objAutorizacionfexv1.Cuit            = Cuit;
                objAutorizacionWSCT                  = new ar.gov.afip.WSCT.AuthRequestType();
                objAutorizacionWSCT.token            = Token;
                objAutorizacionWSCT.sign             = Sign;
                objAutorizacionWSCT.cuitRepresentada = Cuit;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#54
0
        static async Task MainAsync()
        {
            // rename the private_key.pem.example to private_key.pem and put your JWT private key in the file
            var privateKey = File.ReadAllText("private_key.pem");

            var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);

            // Proxy configuration - set isProxyEnabled = true if using Fiddler!!
            if (isProxyEnabled != false)
            {
                System.Net.WebProxy webProxy   = new System.Net.WebProxy("http://127.0.0.1:8888");
                NetworkCredential   credential = new NetworkCredential("testUser", "testPass");
                webProxy.Credentials = credential;
                boxConfig.WebProxy   = webProxy;
            }

            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.AdminToken();

            Console.WriteLine("Admin Token: " + adminToken);
            Console.WriteLine();

            var adminClient = boxJWT.AdminClient(adminToken);

            var adminFunc = new Func(adminClient);

            adminFunc.GetFolderItems();

            var       userId     = "3768478578";
            var       userToken  = boxJWT.UserToken(userId); // valid for 60 minutes so should be cached and re-used
            BoxClient userClient = boxJWT.UserClient(userToken, userId);

            var userFunc = new Func(userClient);

            userFunc.GetFolderItems();

            // Stream fileContents = await userClient.FilesManager.DownloadStreamAsync(id: "675996854920"); // Download the file 675996854920

            // var userRequest = new BoxUserRequest() { Name = "test appuser", IsPlatformAccessOnly = true };
            // var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);
            // Console.WriteLine("Created App User");

            // var userToken = boxJWT.UserToken(appUser.Id);
            // var userClient = boxJWT.UserClient(userToken, appUser.Id);

            // var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();
            // Console.WriteLine("\nApp User Details:");
            // Console.WriteLine("\tId: {0}", userDetails.Id);
            // Console.WriteLine("\tName: {0}", userDetails.Name);
            // Console.WriteLine("\tStatus: {0}", userDetails.Status);
            // Console.WriteLine();

            // await adminClient.UsersManager.DeleteEnterpriseUserAsync(appUser.Id, false, true);
            // Console.WriteLine("Deleted App User");
        }
示例#55
0
        //代理测试
        private void button_test_Click(object sender, EventArgs e)
        {
            String ip   = textBox_testip.Text;
            String port = textBox_testport.Text;

            url   = textBox_testurl.Text;
            proxy = new WebProxy(ip, Convert.ToInt32(port));
            System.Threading.Thread thd = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadFunc));
            thd.Start();
        }
示例#56
0
        /// <summary>
        /// 设置Web代理
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public static void SetHttpProxy(string host, string port, string username, string password)
        {
            ICredentials cred;

            cred = new NetworkCredential(username, password);
            if (!string.IsNullOrEmpty(host))
            {
                _webproxy = new CoreWebProxy(new Uri(host + ":" + port ?? "80"), cred);
            }
        }
示例#57
0
        private static void fillProxy(HttpWebRequest request)
        {
            var proxys = GetProxyListFromCache();
            var proxy  = proxys[new Random().Next(0, proxys.Count - 1)];

            System.Net.WebProxy wp = new System.Net.WebProxy(proxy);
            wp.BypassProxyOnLocal = false;

            request.Proxy = wp;
        }
        public async Task GetCredentialsAsync_SecondCallHasRetryTrue()
        {
            // Arrange
            IEnumerable <ICredentialProvider> providers = new[] { _mockProvider.Object };
            var service = new CredentialService(
                new AsyncLazy <IEnumerable <ICredentialProvider> >(() => Task.FromResult(providers)),
                nonInteractive: false,
                handlesDefaultCredentials: true);

            _mockProvider.Setup(
                x => x.GetAsync(
                    It.IsAny <Uri>(),
                    It.IsAny <IWebProxy>(),
                    It.IsAny <CredentialRequestType>(),
                    It.IsAny <string>(),
                    It.IsAny <bool>(),
                    It.IsAny <bool>(),
                    It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new CredentialResponse(new NetworkCredential())));
            var uri1     = new Uri("http://uri1");
            var webProxy = new WebProxy();

            // Act
            await service.GetCredentialsAsync(
                uri1,
                proxy : null,
                type : CredentialRequestType.Unauthorized,
                message : null,
                cancellationToken : CancellationToken.None);

            await service.GetCredentialsAsync(
                uri1,
                webProxy,
                type : CredentialRequestType.Unauthorized,
                message : null,
                cancellationToken : CancellationToken.None);

            // Assert
            _mockProvider.Verify(x => x.GetAsync(
                                     uri1,
                                     null,
                                     /*type*/ CredentialRequestType.Unauthorized,
                                     /*message*/ null,
                                     /*isRetry*/ false,
                                     /*nonInteractive*/ false,
                                     CancellationToken.None));
            _mockProvider.Verify(x => x.GetAsync(
                                     uri1,
                                     webProxy,
                                     /*type*/ CredentialRequestType.Unauthorized,
                                     /*message*/ null,
                                     /*isRetry*/ true,
                                     /*nonInteractive*/ false,
                                     CancellationToken.None));
        }
示例#59
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static bool IsWebServiceAvaiable(string url, int timeOut)
        {
            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                bool           useProxy         = false;
                if (ConfigurationManager.AppSettings["UseProxy"] != null)
                {
                    if (ConfigurationManager.AppSettings["UseProxy"].ToString() == "1")
                    {
                        useProxy = true;
                    }
                }

                if (useProxy)
                {
                    string strDomain = ConfigurationManager.AppSettings["Domain"].ToString();
                    //域访问名
                    string strUserName = ConfigurationManager.AppSettings["UserName"].ToString();
                    //域访问密码
                    string strPassWord = ConfigurationManager.AppSettings["PassWord"].ToString();
                    //代理地址
                    string strHost = ConfigurationManager.AppSettings["Host"].ToString();
                    //代理端口
                    int strPort = Convert.ToInt32(ConfigurationManager.AppSettings["Port"].ToString());
                    //设置代理
                    System.Net.WebProxy oWebProxy = new System.Net.WebProxy(strHost, strPort);

                    // 获取或设置提交给代理服务器进行身份验证的凭据
                    oWebProxy.Credentials = new System.Net.NetworkCredential(strUserName, strPassWord, strDomain);


                    myHttpWebRequest.Proxy = oWebProxy;
                }
                myHttpWebRequest.Timeout = timeOut * 1000;
                using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse())
                {
                    return(true);
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                return(false);
            }
            return(false);
        }
示例#60
0
        /// <summary>
        /// 填充代理
        /// </summary>
        /// <param name="proxyUri"></param>
        private static void fillProxy(HttpWebRequest request)
        {
            //IP: 帐号: tets1106密码: tets1106开通成功!http端口:808
            //创建 代理服务器设置对象 的实例
            System.Net.WebProxy wp = new System.Net.WebProxy("123.249.2.2:888");
            //代理服务器需要验证
            wp.BypassProxyOnLocal = false;
            //用户名密码
            wp.Credentials = new NetworkCredential("te1107", "te1107");

            request.Proxy = wp;
        }