Beispiel #1
0
        /// <summary>
        /// Retrieve the stock price or delta (change in price)
        /// depending on what the user specified to watch for
        /// </summary>
        private void CheckStock(object sender, EventArgs e)
        {
            // Test for internet connection
            if (Utilities.ConnectedToInternet())
            {
                internetFlag = true;
                try
                {
                    // Retrieve XML document
                    string url = "http://www.google.com/ig/api?stock=" + stockSymbol;

                    WebRequest             webRequest    = WebRequest.Create(url);
                    HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                    webRequest.CachePolicy = noCachePolicy;

                    using (WebResponse webResponse = webRequest.GetResponse())
                    {
                        using (Stream responseStream = webResponse.GetResponseStream())
                        {
                            StreamReader s         = new StreamReader(responseStream, Encoding.GetEncoding(1252));
                            XmlReader    stockData = XmlReader.Create(s);

                            string readTo = changeParam ? "change" : "last";
                            stockData.ReadToFollowing(readTo);
                            double livePrice = Double.Parse(stockData.GetAttribute("data"));

                            // if the stock is above the watching price and user wants to trigger above
                            // OR
                            // if stock is below watching price and the user wants to trigger below
                            // stock price > 0 for all non-negative testing
                            if ((stockPrice > 0 && ((abovePrice && livePrice >= stockPrice) || (!abovePrice && livePrice <= stockPrice))) ||
                                ((abovePrice && livePrice <= stockPrice) || (!abovePrice && livePrice >= stockPrice)))
                            {
                                // logic for when to Trigger()
                                // trigger once when passed, then trigger again once barrier has been reset
                                // ELSE IF
                                // trigger on every pass AND the stock price is at a "reset point" enables ability to trigger on re-pass of point
                                if (!hasPassed)
                                {
                                    hasPassed = true;
                                    Trigger();
                                }
                                else if ((triggerEvery && (abovePrice && livePrice >= stockPrice + PriceOffset)) || (!abovePrice && livePrice <= stockPrice - PriceOffset))
                                {
                                    hasPassed = false;
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            else if (internetFlag)
            {
                internetFlag = false;
                ErrorLog.AddError(ErrorType.Warning, String.Format(Strings.Internet_NotConnected, "Stock"));
            }
        }
Beispiel #2
0
        private static HttpWebRequest CreateRequest(string url, string method)
        {
            int    timeout   = Convert.ToInt16(ConfigurationManager.AppSettings["timeout"]);
            string userAgent = ConfigurationManager.AppSettings["userAgent"];

            try
            {
                var uri     = new Uri(url);
                var request = (HttpWebRequest)WebRequest.Create(uri);
                if (method != "GET")
                {
                    WebRequest.DefaultWebProxy = new WebProxy();
                    request.Timeout            = timeout;
                    request.UserAgent          = userAgent;
                    var policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
                    HttpWebRequest.DefaultCachePolicy = policy;
                    var noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                    request.CachePolicy = noCachePolicy;
                }
                return(request);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                return(null);
            }
        }
        private void ApplyBtn_Click(object sender, RoutedEventArgs e)
        {
            CloseBtn.IsEnabled = false;
            ApplyBtn.IsEnabled = false;
            try
            {
                Log.Debug("User requests upgrade to new version");
                localMsiFilePath = string.Concat(Path.GetTempPath(), Path.DirectorySeparatorChar, "Feedling.msi");

                var nocachepolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

                var wc = new WebClient {
                    CachePolicy = nocachepolicy
                };

                wc.DownloadProgressChanged += wc_DownloadProgressChanged;
                wc.DownloadFileCompleted   += wc_DownloadFileCompleted;
                wc.DownloadFileAsync(new Uri(remoteMsiPath), localMsiFilePath);
            }
            catch (Exception ex)
            {
                Log.Error("Error Applying update", ex);
                UpdateDescription.Text = string.Format(Properties.Resources.UpdatesErrorApplyText, ex.Message);
                CloseBtn.IsEnabled     = true;
            }
        }
        /// <summary>
        /// 设置请求基本信息
        /// </summary>
        /// <param name="request">request</param>
        /// <returns>HttpWebRequest</returns>
        private static HttpWebRequest GetHttpWebRequest(Request request)
        {
            Uri                    uri        = CreateUri(request);
            HttpWebRequest         webRequest = WebRequest.CreateHttp(uri);
            HttpRequestCachePolicy policy     = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            webRequest.CachePolicy     = policy;
            webRequest.Timeout         = request.Timeout;
            webRequest.KeepAlive       = request.KeepAlive;
            webRequest.Method          = request.HttpMethod.ToString();
            webRequest.CookieContainer = request.Cookie;
            webRequest.Referer         = request.Referer;
            webRequest.UserAgent       = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)";
            webRequest.Headers.Add("Cache-Control", "no-cache");
            webRequest.Accept      = "*/*";
            webRequest.Credentials = CredentialCache.DefaultCredentials;

            SetProxy(webRequest, request);

            SetCertificate(webRequest, request);

            SetParameters(webRequest, request);

            return(webRequest);
        }
Beispiel #5
0
        //</snippet3>

        //<snippet4>
        public static void DisplayPolicyDetails(HttpRequestCachePolicy policy)
        {
            Console.WriteLine("Synchronize date: {0}", policy.CacheSyncDate);
            Console.WriteLine("Max age:   {0}", policy.MaxAge);
            Console.WriteLine("Max stale: {0}", policy.MaxStale);
            Console.WriteLine("Min fresh: {0}", policy.MinFresh);
        }
Beispiel #6
0
        /* send http post xml  document request
         * return xml document
         */
        private static XmlDocument XmlRequestPostData(string url, string postData)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] data = encoding.GetBytes(postData);

            request.Method        = "POST";
            request.Accept        = "text/xml";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            request.CachePolicy = noCachePolicy;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(response.GetResponseStream());
                return(xmlDoc);
            }
        }
Beispiel #7
0
        private static string MakeBungieRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://www.bungie.net/Platform/{url.Trim()}");

            request.Headers.Add("X-API-Key", @"C95158E80AD34135845C7D6118F2A7B2");
            request.Headers.Add("X-csrf", @"6645961750234506012");
            request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.Accept    = "*/*";
            request.KeepAlive = true;
            request.AutomaticDecompression = DecompressionMethods.GZip;
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            request.CachePolicy = noCachePolicy;

            var response       = (HttpWebResponse)request.GetResponse();
            var responseHeader = response.Headers.ToString();

            // Open the stream using a StreamReader for easy access.
            var reader       = new StreamReader(response.GetResponseStream());
            var responseBody = reader.ReadToEnd();

            // Clean up the streams.
            reader.Close();
            response.Close();

            return(responseBody);
        }
Beispiel #8
0
        private static string web2string(string url)
        {
            var sb = new StringBuilder();

            byte[] buffer        = new byte[8192];
            var    request       = (HttpWebRequest)WebRequest.Create(url);
            var    noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            request.CachePolicy = noCachePolicy;
            var response   = (HttpWebResponse)request.GetResponse();
            var resStream  = response.GetResponseStream();
            var tempString = string.Empty;
            var count      = 0;

            do
            {
                count = resStream.Read(buffer, 0, buffer.Length);
                if (count != 0)
                {
                    tempString = Encoding.UTF8.GetString(buffer, 0, count);
                    sb.Append(tempString);
                }
            }while (count > 0);
            return(sb.ToString());
        }
Beispiel #9
0
        public HttpWebResponse HTTPGetRequest(string baseUrl, string action, object data, string accessToken)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

#if DEBUG
            ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                                                                System.Security.Cryptography.X509Certificates.X509Chain chain,
                                                                                System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return(true); // **** IGNORE ANY SSL ISSUES/VALIDATION
            };
#endif
            var request       = (HttpWebRequest)WebRequest.Create(baseUrl + action);
            var noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
            request.CachePolicy = noCachePolicy;

            request.Method = "GET";

            if (!string.IsNullOrEmpty(accessToken))
            {
                request.Headers.Add("Authorization", "Bearer " + accessToken);
            }

            var response = (HttpWebResponse)request.GetResponse();
            return(response);
        }
        private static void WebApiCall()
        {
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);

            HttpWebRequest.DefaultCachePolicy = policy;

            var req = WebRequest.CreateHttp(CriptoCoin.BTC);                                                         // Cria a requisição

            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); // Seta a requisição sem Cache

            req.CachePolicy = noCachePolicy;
            req.Method      = "GET";

            try
            {
                var          resposta    = req.GetResponse();                     // Faz a requisição
                var          streamDados = resposta.GetResponseStream();
                StreamReader reader      = new StreamReader(streamDados);         // Pega a resposta
                object       objResponse = reader.ReadToEnd();
                var          result      = JObject.Parse(objResponse.ToString()); // Parse JSON
                decimal      price       = Math.Round(Convert.ToDecimal(result["ticker"]["last"]), 2);

                Console.WriteLine(String.Format("Preço Atual : {0} || Horario : {1}", price, DateTime.Now));

                streamDados.Close();
                resposta.Close();
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error : " + e.Message);
            }
        }
Beispiel #11
0
        private Stream ResponseStreamPOST(string Url, string Command, WebProxy Proxy)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(Command);

            // Объект, с помощью которого будем отсылать запрос и получать ответ.
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            HttpWebRequest.DefaultCachePolicy = policy;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

            request.Method        = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType   = "text/xml";

            if (Proxy != null)
            {
                request.Proxy = Proxy;
            }

            // Пишем наш XML-запрос в поток
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            // Получаем ответ
            HttpWebResponse response       = (HttpWebResponse)request.GetResponse();
            Stream          responsestream = response.GetResponseStream();

            return(responsestream);
        }
Beispiel #12
0
        public static async Task <string> GetAsync(string url)
        {
            string cachedValue = CheckCache(url);

            if (!string.IsNullOrWhiteSpace(cachedValue))
            {
                Console.WriteLine(String.Format("using cached response for url:{0}", url));
                return(cachedValue);
            }

            HttpRequestCachePolicy requestPolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromDays(1));
            HttpWebRequest         request       = (HttpWebRequest)WebRequest.Create(url);

            request.CachePolicy = requestPolicy;

            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string result = await reader.ReadToEndAsync();

                        Console.WriteLine(String.Format("Response achieved for url:{0} , direclty from server", url));
                        SaveDataToCache(url, result);
                        return(result);
                    }
        }
Beispiel #13
0
        public static string Read(string url, bool isUseCache = true, int timeout = 10000)
        {
            string strRel = string.Empty;

            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Timeout = timeout;
                if (!isUseCache)
                {
                    HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                    request.CachePolicy = noCachePolicy;
                }
                HttpWebResponse     response = (HttpWebResponse)request.GetResponse();
                WebHeaderCollection header   = response.Headers;

                var encoding = ASCIIEncoding.ASCII;
                using (var reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    strRel = reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("WebHelper:Read exception:" + e.Message);
            }

            return(strRel);
        }
Beispiel #14
0
        private static bool ChequearUrl(string url)
        {
            HttpWebRequest  req;
            HttpWebResponse resp;

            try
            {
                // Set a default policy level for the "http:" and "https" schemes.
                HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
                HttpWebRequest.DefaultCachePolicy = policy;
                req         = (HttpWebRequest)WebRequest.Create(url);
                req.Timeout = 100000;

                // Define a cache policy for this request only.
                HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                req.CachePolicy = noCachePolicy;
                resp            = (HttpWebResponse)req.GetResponse();
                req             = null;
                if (resp.StatusCode.ToString().Equals("OK"))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;
                return(false);
            }
        }
Beispiel #15
0
        protected internal virtual HttpWebRequest SendPost()
        {
            streamLogger.Debug("Opening connection to " + this.address);
            Uri            requestUri = new Uri(this.address);
            HttpWebRequest request    = (HttpWebRequest)WebRequest.Create(requestUri);

            if (request == null)
            {
                streamLogger.Debug("Failed connection to " + this.address);
                throw new IOException("Connection failed");
            }
            request.Method = "POST";
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            request.CachePolicy = policy;
            request.KeepAlive   = false;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept      = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
            request.UserAgent   = "Lightstreamer .NET Client";
            Stream requestStream = request.GetRequestStream();

            if (this.request != null)
            {
                if (streamLogger.IsDebugEnabled)
                {
                    streamLogger.Debug("Posting data: " + this.request);
                }
                byte[] bytes = new ASCIIEncoding().GetBytes(this.request);
                requestStream.Write(bytes, 0, bytes.Length);
            }
            requestStream.Flush();
            requestStream.Close();
            return(request);
        }
Beispiel #16
0
        public void thread_getnewscount()
        {
            Thread.Sleep(2500);


            string major    = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Major.ToString().PadLeft(2, '0');
            string minor    = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Minor.ToString().PadLeft(2, '0');
            string build    = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Build.ToString().PadLeft(2, '0');
            string revision = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Revision.ToString().PadLeft(2, '0');

            Console.WriteLine("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            Console.WriteLine(major + "." + minor + "." + build + "." + revision);


            string tmp_verze = major + minor + build + revision;
            string remoteUrl = "http://sorgair.com/api/news.php?version=" + tmp_verze;

            Console.WriteLine(remoteUrl);
            HttpWebRequest         httpRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
            HttpRequestCachePolicy policy      = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            HttpWebRequest.DefaultCachePolicy = policy;

            httpRequest.CachePolicy = policy;
            WebResponse  response = httpRequest.GetResponse();
            StreamReader reader   = new StreamReader(response.GetResponseStream());
            string       result   = reader.ReadToEnd();

            Console.WriteLine(result);


            this.Invoke(() => VM.BIND_NEWS_COUNT = result);
        }
Beispiel #17
0
        private static byte[] GetRBLoad(String aslocation)
        {
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            WebRequest asrequest = WebRequest.Create(aslocation);

            asrequest.CachePolicy = noCachePolicy;

            MemoryStream asMemoryStream = new MemoryStream(0x10000);

            Console.WriteLine("Downloading " + aslocation);
            using (Stream asResponseStream = asrequest.GetResponse().GetResponseStream())
            {
                byte[] buffer = new byte[0x1000];
                int    bytes;
                while ((bytes = asResponseStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    asMemoryStream.Write(buffer, 0, bytes);
                }
            }

            // MemoryStream -> byte[]
            byte[] asbytes = asMemoryStream.ToArray();

            return(asbytes);
        }
Beispiel #18
0
        /// <summary>
        /// <param name="resource">The kind of resource to ask for</param>
        /// <param name="argument">Any argument that needs to be passed, such as a project key</param>
        /// <param name="data">More advanced data sent in POST requests</param>
        /// <param name="method">Either GET or POST</param>
        /// <param name="APIBase">Base or DevStatus</param>
        /// <returns></returns>
        public static string RunQuery(string url, string resource = null, string argument = null, string data = null, string method = "GET")
        {
            try
            {
                HttpWebRequest         request       = WebRequest.Create(url) as HttpWebRequest;
                HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                request.CachePolicy = noCachePolicy;
                request.ContentType = "application/json";
                request.Method      = method;

                if (data != null)
                {
                    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                    {
                        writer.Write(data);
                    }
                }

                string base64Credentials = GetEncodedCredentials();
                request.Headers.Add("Authorization", "Basic " + base64Credentials);

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                string result = string.Empty;
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                }
                return(result);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #19
0
        public static HttpWebRequest ConstructWebRequest(
            string requestUri,
            EPassportPolicyId passportTicketType,
            HttpRequestCachePolicy cachePolicy,
            bool fKeepAlive,
            bool acceptGZipEncoding)
        {
            string absoluteUri = new Uri(requestUri).AbsoluteUri;

            if (absoluteUri != requestUri)
            {
                int num = TraceSwitches.DataProviderSwitch.TraceWarning ? 1 : 0;
                requestUri = absoluteUri;
            }
            if (cachePolicy == HttpRequestCachePolicy.Default && UriResourceTracker.Instance.IsResourceModified(requestUri))
            {
                cachePolicy = HttpRequestCachePolicy.Refresh;
                UriResourceTracker.Instance.SetResourceModified(requestUri, false);
            }
            HttpWebRequest request = HttpWebRequest.Create(requestUri);

            request.KeepAlive        = fKeepAlive;
            request.CancelOnShutdown = true;
            SetCommonHeaders(request, passportTicketType, cachePolicy, acceptGZipEncoding);
            int num1 = TraceSwitches.DataProviderSwitch.TraceWarning ? 1 : 0;

            return(request);
        }
Beispiel #20
0
        /// <summary>
        /// Uses <see cref="HttpWebRequest"/> and <see cref="HttpWebResponse"/> to create requests to the API.
        /// Returns the JSON result.
        /// </summary>
        /// <param name="url">The url of the endpoint</param>
        /// <returns>The JSON Result</returns>
        private async Task <string> MakeRequestAsync(string url)
        {
            // Set a default policy level for the "http:" and "https" schemes.
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);

            HttpWebRequest.DefaultCachePolicy = policy;

            //Create request
            var request = WebRequest.Create(url + Values.AppId);

            // Define a cache policy for this request only.
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            request.CachePolicy = noCachePolicy;

            request.ContentType = "application/json; charset=utf-8";
            string t;
            var    response = (HttpWebResponse)await request.GetResponseAsync();

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                t = sr.ReadToEnd();
            }

            return(t);
        }
Beispiel #21
0
        private HttpWebRequest method_2(string string_1, string string_2)
        {
            Uri requestUri = new Uri(string_1);

            if (requestUri.Scheme == "https")
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.method_3);
            }
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);

            HttpWebRequest.DefaultCachePolicy = policy;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            request.AllowAutoRedirect         = false;
            request.AllowWriteStreamBuffering = false;
            request.Method = string_2;
            if (this.webProxy_0 != null)
            {
                request.Proxy = this.webProxy_0;
            }
            foreach (string str in this.webHeaderCollection_0.Keys)
            {
                request.Headers.Add(str, this.webHeaderCollection_0[str]);
            }
            this.webHeaderCollection_0.Clear();
            return(request);
        }
Beispiel #22
0
        /// <summary>
        /// 设置GetData和PostData的通用Headers
        /// </summary>
        /// <param name="myRequest"></param>
        /// <param name="requestHeaders"></param>
        /// <param name="cookieStrings"></param>
        private static void SetRequestHeadersForCommon(HttpWebRequest myRequest, string requestHeaders, string cookieStrings)
        {
            AddRequestHeaders(myRequest, requestHeaders);
            //强制取消缓存,同浏览器Disable Cache
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            myRequest.CachePolicy           = noCachePolicy;
            myRequest.AllowAutoRedirect     = true;
            myRequest.Proxy                 = null;
            myRequest.UseDefaultCredentials = true;
            //多线程超时解决办法。对于前面多个request。其都是keepalive为true,以及多个response也没有close
            ServicePointManager.DefaultConnectionLimit = 10;
            //如果没有填写头部连接属性则默认关闭【基础连接已经关闭: 服务器关闭了本应保持活动状态的连接。】
            if (myRequest.Headers["Connection"] == null)
            {
                myRequest.KeepAlive = false;
            }

            if (myRequest.Headers["User-Agent"] == null)
            {
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36";
            }

            if (cookieStrings.Length > 0)
            {
                if (myRequest.Headers["Cookie"] != null)
                {
                    myRequest.Headers.Remove("Cookie");
                }
                myRequest.Headers.Add("Cookie", cookieStrings);
            }
        }
Beispiel #23
0
        static internal void ConfigCachePolicy(WebRequest request, bool isRefresh)
        {
            HttpWebRequest httpRequest = request as HttpWebRequest;

            if (httpRequest != null)
            {
                // Setting CachePolicy to the default level if it is null.
                if (request.CachePolicy == null || request.CachePolicy.Level != RequestCacheLevel.Default)
                {
                    if (isRefresh)
                    {
                        if (_httpRequestCachePolicyRefresh == null)
                        {
                            _httpRequestCachePolicyRefresh = new HttpRequestCachePolicy(HttpRequestCacheLevel.Refresh);
                        }
                        request.CachePolicy = _httpRequestCachePolicyRefresh;
                    }
                    else
                    {
                        if (_httpRequestCachePolicy == null)
                        {
                            _httpRequestCachePolicy = new HttpRequestCachePolicy();
                        }
                        request.CachePolicy = _httpRequestCachePolicy;
                    }
                }
            }
        }
Beispiel #24
0
        /// <summary>
        /// 创建HTTP请求
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <returns></returns>
        private HttpWebRequest CreateRequest(string url, string method)
        {
            Uri uri = new Uri(url);

            if (uri.Scheme == "https")
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult);
            }

            // Set a default policy level for the "http:" and "https" schemes.
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);

            HttpWebRequest.DefaultCachePolicy = policy;

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

            request.AllowAutoRedirect         = false;
            request.AllowWriteStreamBuffering = false;
            request.Method = method;
            if (proxy != null)
            {
                request.Proxy = proxy;
            }
            request.CookieContainer = cc;
            foreach (string key in requestHeaders.Keys)
            {
                request.Headers.Add(key, requestHeaders[key]);
            }
            requestHeaders.Clear();
            return(request);
        }
Beispiel #25
0
        private static bool downloadFile(string exeDownload, string url, bool hidden = false)
        {
            int bufferSize = 1024;

            byte[] buffer    = new byte[bufferSize];
            int    bytesRead = 0;
            bool   cerrar    = false;

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            var webrequest = (HttpWebRequest)WebRequest.Create(url);
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            webrequest.CachePolicy = noCachePolicy;

            webrequest.Method = WebRequestMethods.Http.Get;
            if (File.Exists(exeDownload))
            {
                File.SetAttributes(exeDownload, FileAttributes.Normal);
            }
            FileStream fileStream = File.Create(exeDownload);

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        bytesRead = stream.Read(buffer, 0, bufferSize);
                        if (bytesRead == 0)
                        {
                            cerrar = true;
                        }

                        while (bytesRead != 0)
                        {
                            fileStream.Write(buffer, 0, bytesRead);
                            bytesRead = stream.Read(buffer, 0, bufferSize);
                        }
                        stream.Close();
                    }
                    response.Close();
                }
            }
            catch
            {
                cerrar = true;
            }
            fileStream.Close();
            if (hidden)
            {
                File.SetAttributes(exeDownload, FileAttributes.Hidden);
            }
            if (cerrar)
            {
                File.SetAttributes(exeDownload, FileAttributes.Normal);
                File.Delete(exeDownload);
            }
            return(!cerrar);
        }
Beispiel #26
0
        public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;

            byte[]                 byteArray     = dataEncode.GetBytes(paramData); //转化
            HttpWebRequest         request       = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            request.CachePolicy   = noCachePolicy;
            request.Method        = WebRequestMethods.Http.Post;
            request.ContentType   = "application/x-www-form-urlencoded";
            request.UserAgent     = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143  Safari/537.36";
            request.ContentLength = byteArray.Length;
            Stream newStream = request.GetRequestStream();

            newStream.Write(byteArray, 0, byteArray.Length);//写入参数
            newStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader    sr       = new StreamReader(response.GetResponseStream(), dataEncode);

            ret = sr.ReadToEnd();
            sr.Close();
            response.Close();
            return(ret);
        }
Beispiel #27
0
        /// <summary>
        /// 创建一个WebRequest
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="method">POST/GET</param>
        /// <returns></returns>
        protected HttpWebRequest createRequest(string url, string method)
        {
            Uri uri = new Uri(url);

            if (uri.Scheme == "https")
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.checkValidationResult);
            }

            // Set a default policy level for the "http:" and "https" schemes.
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);

            HttpWebRequest.DefaultCachePolicy = policy;

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

            request.AllowAutoRedirect         = false;
            request.AllowWriteStreamBuffering = false;
            request.Method = method;
            if (this.Proxy != null)
            {
                request.Proxy = this.Proxy;
            }
            if (this.CookieContainer != null)
            {
                request.CookieContainer = this.CookieContainer;
            }
            request.Accept    = "*/*";
            request.KeepAlive = true;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
            return(request);
        }
Beispiel #28
0
        protected void SetRequestDefaultProperties(HttpWebRequest request, int requestTimeout)
        {
            request.UserAgent = DefaultProperties.DefaultUserAgent;

            //
            //TimeOut 설정
            //
            if (requestTimeout > 0)
            {
                request.Timeout = requestTimeout;
            }


            if (DefaultProperties.DefaultIsSetCachePolicy)
            {
                HttpRequestCachePolicy httpRequestCachePolicy = new HttpRequestCachePolicy(DefaultProperties.DefaultCacheLevel);
                request.CachePolicy = httpRequestCachePolicy;
            }

            ///
            /// Expect100Continue 무시
            ///
            request.ServicePoint.Expect100Continue = DefaultProperties.DefaultIsExpect100Continue;

            request.ContentType = DefaultContentType;
        }
Beispiel #29
0
        private static string getHTTPSRequest(string strRequest)
        {
            try
            {
                WebRequest ThisRequest = WebRequest.Create(strRequest);
                ThisRequest.ContentType = "application/x-www-form-urlencoded";
                HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                ThisRequest.CachePolicy = noCachePolicy;
                ThisRequest.Method      = "GET";

                System.Text.ASCIIEncoding Encoder = new System.Text.ASCIIEncoding();
                byte[] BytesToSend = Encoder.GetBytes(strRequest);
                ServicePointManager.Expect100Continue           = true;
                ServicePointManager.SecurityProtocol            = SecurityProtocolType.Tls12;
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                HttpWebResponse TheirResponse = (HttpWebResponse)ThisRequest.GetResponse();

                StreamReader sr          = new StreamReader(TheirResponse.GetResponseStream());
                string       strResponse = sr.ReadToEnd();
                sr.Close();

                return(strResponse);
            }
            catch (Exception ex)
            {
                return("");
            }
        }
 public void FetchIndex()
 {
     try
     {
         HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
         HttpWebRequest.DefaultCachePolicy = policy;
         HttpWebRequest req = WebRequest.CreateHttp("https://github.com/skyloutyr/VSCCScripts/raw/master/index.json");
         req.Timeout = 5000;
         HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
         req.CachePolicy = noCachePolicy;
         using (WebResponse response = req.GetResponse())
         {
             using (Stream s = response.GetResponseStream())
             {
                 using (StreamReader sr = new StreamReader(s))
                 {
                     string result = sr.ReadToEnd();
                     this.Dispatcher.Invoke(() => this.HandleIndex(result, null));
                 }
             }
         }
     }
     catch (Exception e)
     {
         this.Dispatcher.Invoke(() => this.HandleIndex(null, e));
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpRequestOptions"/> class.
        /// </summary>
        public HttpRequestOptions()
        {
            EnableHttpCompression = true;
            BufferContent = true;

            CachePolicy = HttpRequestCachePolicy.None;

            RequestHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        }