Наследование: WebResponse, ISerializable, IDisposable
        public string Create(string url)
        {
            try
            {
                // setup web request to tinyurl
                request = (HttpWebRequest)WebRequest.Create(string.Format(TINYURL_ADDRESS_TEMPLATE, url));
                request.Timeout = REQUEST_TIMEOUT;
                request.UserAgent = USER_AGENT;

                // get response
                response = (HttpWebResponse)request.GetResponse();

                // prase response stream to string
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(ENCODING_NAME));

                // convert the buffer into string and store in content
                StringBuilder sb = new StringBuilder();
                while (reader.Peek() >= 0)
                {
                    sb.Append(reader.ReadLine());
                }
                return sb.ToString();
            }
            catch (Exception)
            {
                return null;
            }
        }
Пример #2
1
 private static void DisposeObject(ref HttpWebRequest request, ref HttpWebResponse response,
     ref Stream responseStream, ref StreamReader reader)
 {
     if (request != null)
     {
         request = null;
     }
     if (response != null)
     {
         response.Close();
         response = null;
     }
     if (responseStream != null)
     {
         responseStream.Close();
         responseStream.Dispose();
         responseStream = null;
     }
     if (reader != null)
     {
         reader.Close();
         reader.Dispose();
         reader = null;
     }
 }
Пример #3
1
 public static void Download()
 {
     using (WebClient wcDownload = new WebClient())
     {
         try
         {
             webRequest = (HttpWebRequest)WebRequest.Create(optionDownloadURL);
             webRequest.Credentials = CredentialCache.DefaultCredentials;
             webResponse = (HttpWebResponse)webRequest.GetResponse();
             Int64 fileSize = webResponse.ContentLength;
             strResponse = wcDownload.OpenRead(optionDownloadURL);
             strLocal = new FileStream(optionDownloadPath, FileMode.Create, FileAccess.Write, FileShare.None);
             int bytesSize = 0;
             byte[] downBuffer = new byte[2048];
             downloadForm.Refresh();
             while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
             {
                 strLocal.Write(downBuffer, 0, bytesSize);
                 PercentProgress = Convert.ToInt32((strLocal.Length * 100) / fileSize);
                 pBar.Value = PercentProgress;
                 pLabel.Text = "Downloaded " + strLocal.Length + " out of " + fileSize + " (" + PercentProgress + "%)";
                 downloadForm.Refresh();
             }
         }
         catch { }
         finally
         {
             webResponse.Close();
             strResponse.Close();
             strLocal.Close();
             extractAndCleanup();
             downloadForm.Hide();
         }
     }
 }
Пример #4
0
 protected override void When()
 {
     var req = CreateRawJsonPostRequest(TestStream + "/metadata", "POST", new {A = "1"},
         DefaultData.AdminNetworkCredentials);
     req.Headers.Add("ES-EventId", Guid.NewGuid().ToString());
     _response = (HttpWebResponse) req.GetResponse();
 }
Пример #5
0
        public static Image DownloadBinaryFromInternet(string Inurl)
        {
            Uri    url          = new Uri(Inurl);
            string urlHost      = url.Host;
            Image  BookmarkIcon = null;

            if (url.HostNameType == UriHostNameType.Dns)
            {
                string iconUrl = Inurl;
                try
                {
                    HttpWebRequest             request  = (HttpWebRequest)HttpWebRequest.Create(iconUrl);
                    System.Net.HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    System.IO.Stream           stream   = response.GetResponseStream();
                    BookmarkIcon = Image.FromStream(stream);
                }
                catch (Exception exp)
                {
                    AppController.Current.Logger.writeToLogfile(exp);
                }
                return(BookmarkIcon);
            }
            else
            {
                return(null);
            }
        }
Пример #6
0
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            string username = ConvertMD5(textBoxAccount.Text);
            string password = ConvertSHA1(textBoxPassword.Text);

            try
            {
                System.Net.HttpWebRequest WebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://bluesheepbot.com/c.php?mdp=" + username + password);

                System.Net.HttpWebResponse WebResponse = (System.Net.HttpWebResponse)WebRequest.GetResponse();
                System.IO.StreamReader     STR         = new System.IO.StreamReader(WebResponse.GetResponseStream());
                string ReadSource = STR.ReadToEnd();
                //MessageBox.Show(ReadSource);
                System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex("Account" + "=(\\d+)");
                MatchCollection matches   = Regex.Matches(ReadSource);
                int             nbPremium = 0;
                foreach (Match match in matches)
                {
                    string[] RegSplit = match.ToString().Split('=');
                    nbPremium = Convert.ToInt32(RegSplit[1]);
                }
                mainfrm = new MainForm(version);
                mainfrm.Show();
                Hide();
            }
            catch (WebException exception)
            {
                MessageBox.Show("Echec de connexion. Vérifiez votre connexion :\n" + exception.Message);
            }
        }
Пример #7
0
        /// <summary>
        /// Get请求(https未做验证考虑)
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="param">参数列表(如果在url中已经追加参数则此值可为null或空字符)</param>
        /// <returns></returns>
        public static TResult WebGetRequest <TResult>(string url, Dictionary <string, string> param, Dictionary <string, string> headers = null) where TResult : class
        {
            HttpWebRequest webRequest = null;

            if (param == null || param.Count == 0)
            {
                webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            }
            else
            {
                url += "?";
                string paramStr = string.Empty;
                for (int i = 0; i < param.Count; i++)
                {
                    paramStr += param.ElementAt(i).Key + "=" + param.ElementAt(i).Value + "&";
                }
                url       += paramStr.Substring(0, paramStr.LastIndexOf("&"));
                webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            }
            webRequest.Method  = "GET";
            webRequest.Timeout = 1000000;
            if (headers != null)
            {
                foreach (var item in headers)
                {
                    webRequest.Headers.Add(item.Key, item.Value);
                }
            }
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse();
            System.IO.StreamReader     reader   = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            string strResult = reader.ReadToEnd();

            return(JsonConvert.DeserializeObject <TResult>(strResult));
        }
        //需要注意的是如果你使用多线程。。C#默认同时只有4个网络线程,如需要破解此限制需要添加代码
        //ServicePointManager.DefaultConnectionLimit = 100;

        //此方法返回一个状态码。。状态码为200是为正常,异常时会返回错误信息。比如超时


        public static bool UrlIsExist(String url, int timeout)
        {
            System.Uri u = null;
            try
            {
                u = new Uri(url);
            }
            catch { return(false); }
            bool isExist = false;

            System.Net.HttpWebRequest r = System.Net.HttpWebRequest.Create(u)
                                          as System.Net.HttpWebRequest;
            r.Method = "HEAD";
            try
            {
                System.Net.HttpWebResponse s = r.GetResponse() as System.Net.HttpWebResponse;
                r.Timeout = timeout;
                if (s.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    isExist = true;
                }
            }
            catch (System.Net.WebException x)
            {
                try
                {
                    isExist = ((x.Response as System.Net.HttpWebResponse).StatusCode !=
                               System.Net.HttpStatusCode.NotFound);
                }
                catch { isExist = (x.Status == System.Net.WebExceptionStatus.Success); }
            }
            return(isExist);
        }
Пример #9
0
 protected void Application_End(object sender, System.EventArgs e)
 {
     if (ConfigurationManager.AppSettings["Installer"] != null)
     {
         return;
     }
     try
     {
         JobsHelp.stop();
         if (string.IsNullOrEmpty(Global.strUrl))
         {
             System.Threading.Thread.Sleep(1000);
             System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Global.strUrl);
             using (System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse())
             {
                 using (httpWebResponse.GetResponseStream())
                 {
                 }
             }
         }
     }
     catch
     {
         Globals.Debuglog("重启动Application_start失败!", "_Debuglog.txt");
     }
 }
Пример #10
0
 public CouchResponse(HttpWebResponse response)
 {
     responseString = response.GetResponseString();
     statusCode = response.StatusCode;
     statusDescription = response.StatusDescription;
     etag = response.Headers["ETag"];
 }
Пример #11
0
        /// <summary>
        /// 图块下载完成的回调
        /// </summary>
        protected override void DownloadComplete()
        {
            try
            {
                download.Verify();

                if (download.SavedFilePath != null && File.Exists(download.SavedFilePath))
                {
                    // Rename from .xxx.tmp -> .xxx
                    File.Move(download.SavedFilePath, SaveFilePath);
                }

                // Make the quad tile reload the new image
                m_quadTile.isInitialized = false;
                QuadTile.DownloadRequest = null;
            }
            catch (WebException caught)
            {
                System.Net.HttpWebResponse response = caught.Response as System.Net.HttpWebResponse;
                if (response != null && response.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    FlagBadFile();
                }
            }
            catch (IOException)
            {
                FlagBadFile();
            }
        }
Пример #12
0
        /// <summary>
        /// 通过Post方式发送并返回Http结果
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Code"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static String Send(String Url, Encoding Code, String postData, string CertPath = "", string CertPwd = "")
        {
            byte[] data = Code.GetBytes(postData);
            if (Url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(Url);
            req.Method  = "POST";
            req.Timeout = 6000;
            //req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            req.ContentType   = "text/xml";
            req.ContentLength = data.Length;
            if (!String.IsNullOrEmpty(CertPath))
            {
                req.ClientCertificates.Add(new X509Certificate(CertPath, CertPwd));
            }
            //发送数据
            System.IO.Stream newStream = req.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
            newStream.Close();

            //获取响应
            HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
            StreamReader    reader     = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string          content    = reader.ReadToEnd().Trim();

            return(content);
        }
Пример #13
0
        /// <summary>
        /// 执行请求,请求接口失败时抛出异常
        /// </summary>
        /// <typeparam name="T">请求的类型</typeparam>
        /// <typeparam name="S">返回的类型</typeparam>
        /// <param name="requestType">接口名称</param>
        /// <param name="obj">请求的参数Json对象</param>
        /// <returns>返回的类型的对象</returns>
        public static S Request <T, S>(T obj)
        {
            string str          = jss.Serialize(obj);
            string paraUrlCoded = KeyValueCombination(str);

            string strURL = @"http://api.fanyi.baidu.com/api/trans/vip/translate";

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.UserAgent   = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Method      = "POST";
            request.Proxy       = null;
            request.Timeout     = 60000;
            byte[] payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            request.ContentLength = payload.Length;
            System.IO.Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.StreamReader     myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string responseText = myreader.ReadToEnd();

            myreader.Close();

            return(jss.Deserialize <S>(responseText));
        }
Пример #14
0
 public static ICMPErrors PingHostHttp(string url, out int dwStop)
 {
     dwStop = -1;
     try
     {
         int dtInicio, dtFim;
         System.Net.HttpWebRequest  hwrReq = null;
         System.Net.HttpWebResponse hwrRes = null;
         dtInicio = System.Environment.TickCount;
         try
         {
             hwrReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new System.Uri(url));
             hwrRes = (System.Net.HttpWebResponse)hwrReq.GetResponse();
         }
         catch
         {
             return(ICMPErrors.ERROR_UNKNOW);
         }
         finally
         {
             if (hwrRes != null)
             {
                 hwrRes.Close();
             }
         }
         dtFim  = System.Environment.TickCount;
         dwStop = dtFim - dtInicio;
         return(ICMPErrors.ERROR_NONE);
     }
     catch
     {
         return(ICMPErrors.ERROR_UNKNOW);
     }
 }
Пример #15
0
        public string GetTitle()
        {
            string title = "";

            System.Net.HttpWebRequest webReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(BaseURL);
            FormMain.UserConfig.SetProxy(webReq);
            System.Net.HttpWebResponse webRes = null;

            try
            {
                webRes = (System.Net.HttpWebResponse)webReq.GetResponse();

                string           returnText;
                System.IO.Stream resStream = webRes.GetResponseStream();

                using (System.IO.StreamReader sr = new System.IO.StreamReader(resStream, GetEncoding()))
                {
                    returnText = sr.ReadToEnd();
                }
                Regex rx = new Regex("<title>(.*?)</title>", RegexOptions.Singleline | RegexOptions.IgnoreCase);

                Match m = rx.Match(returnText);
                if (m.Success)
                {
                    title = HttpUtility.HtmlDecode(m.Groups[1].Value);
                }
            }
            catch (Exception e)
            {
                FormMain.Instance.AddLog(e.Message);
            }
            return(title);
        }
Пример #16
0
        public void DownloadFile(string URL, string filename)
        {
            float percent = 0;

            try
            {
                System.Net.HttpWebRequest  Myrq      = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp      = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long             totalBytes          = myrp.ContentLength;
                System.IO.Stream st                  = myrp.GetResponseStream();
                System.IO.Stream so                  = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by                  = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);

                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    int mypercent = (int)percent;
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
            }
            catch (Exception downee)
            {
                MessageBox.Show(downee.ToString() + "\n\n简短解释:\n下载出错,请检查是否有目录权限;磁盘空间是否已满;若无法解决请进群咨询管理员");
            }
        }
Пример #17
0
        public static string DoPost(string url, Hashtable paramsOfUrl)
        {
            if (url == null)
            {
                throw new Exception("WebService地址为空");
            }
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            // 编辑并Encoding提交的数据
            byte[] data = GetJointBOfParams(paramsOfUrl);

            // 发送请求
            request               = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            Stream stream = request.GetRequestStream();

            stream.Write(data, 0, data.Length);
            stream.Close();

            // 获得回复
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string       result = reader.ReadToEnd();

            reader.Close();
            return(result);
        }
Пример #18
0
        public void DownloadFile(string URL, string filename)
        {
            try
            {
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long             totalBytes     = myrp.ContentLength;
                System.IO.Stream st             = myrp.GetResponseStream();
                System.IO.Stream so             = new System.IO.FileStream(filename, System.IO.FileMode.Create);

                byte[] by = new byte[1024];

                int  realReadLen      = st.Read(by, 0, by.Length);
                long progressBarValue = 0;
                while (realReadLen > 0)
                {
                    so.Write(by, 0, realReadLen);
                    progressBarValue += realReadLen;
                    pbDown.Dispatcher.BeginInvoke(new ProgressBarSetter(SetProgressBar), progressBarValue);
                    realReadLen = st.Read(by, 0, by.Length);
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }
        }
Пример #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MadMimi.Result"/> class.
 /// </summary>
 /// <param name='response'>
 /// An HttpWebResponse which contains the result.
 /// </param>
 public Result(HttpWebResponse response)
 {
     statusCode = response.StatusCode;
     using (StreamReader reader = new StreamReader (response.GetResponseStream ())) {
         body = reader.ReadToEnd ();
     }
 }
Пример #20
0
 private static string GetSchemaString(HttpWebResponse response)
 {
     string result;
     var reader = new StreamReader(response.GetResponseStream());
     result = reader.ReadToEnd();
     return result;
 }
        protected string ReadBodyFromResponse(System.Net.HttpWebResponse response)
        {
            System.IO.Stream       s  = null;
            System.IO.StreamReader sr = null;
            try
            {
                s  = response.GetResponseStream();
                sr = new System.IO.StreamReader(s, enc);
                string body = sr.ReadToEnd();

                if (Kii.Logger != null)
                {
                    Kii.Logger.Debug("Response HTTP {0}\nResponse body : {1}", response.StatusCode, body);
                }

                return(body);
            } finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
                if (s != null)
                {
                    s.Close();
                }
            }
        }
        public DisneyPostRequest(String url, AuthToken token, String partySize, String mealPeriod, String searchDate)
        {
            String parameters = "grant_type=assertion&assertion_type=public&client_id=WDPRO-MOBILE.CLIENT-PROD&partySize=" + partySize + "&mealPeriod=" + mealPeriod + "&searchDate=" + searchDate;

            IDisneyReservationRequest disneyRequest = this;
            HttpWebRequest request = disneyRequest.setHeadersWithAuthorization(url, token);
            HttpWebResponse response = disneyRequest.makeReservationRequest(request, parameters);
            try
            {
                _response = response;
                String responseMessage = disneyRequest.returnResponse(response);
                ResponseMessage = responseMessage;
                WebHeaderCollection responseHeaders = response.Headers;
                _reservationUrl = responseHeaders.Get("Location");

            }
            catch (NullReferenceException err)
            {
                Console.WriteLine(err.Message);

            }

            DisneyGetRequest reservationRequest = new DisneyGetRequest(_reservationUrl, token);
            ResponseMessage = reservationRequest.ResponseMessage;
        }
 public bool GetRequest(string url, string referer)
 {
     bool result = false;
     try
     {
         HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
         httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.70 Safari/533.4";
         httpWebRequest.Referer = referer;
         httpWebRequest.Headers.Add("Cache-Control", "max-age=0");
         httpWebRequest.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
         httpWebRequest.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
         httpWebRequest.Headers.Add("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
         httpWebRequest.Headers.Add("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.3");
         httpWebRequest.AllowAutoRedirect = this.AutoRedirect;
         httpWebRequest.CookieContainer = this.Cookie;
         this.HttpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
         this.GetCookiesFromResponse();
         result = true;
     }
     catch
     {
         result = false;
         return result;
     }
     return result;
 }
Пример #24
0
 public void Delete(string remotename)
 {
     System.Net.HttpWebRequest req  = CreateRequest(System.Net.WebRequestMethods.Http.Post, remotename, "rm=true", false); // rm=true means permanent delete, dl=true would be move to trash.
     Utility.AsyncHttpRequest  areq = new Utility.AsyncHttpRequest(req);
     using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)areq.GetResponse())
     { }
 }
        /// <summary>
        /// Parses HTTP response and creates new instance of this class
        /// </summary>
        /// <param name="response">HTTP response</param>
        /// <returns>New instance of this class</returns>
        internal static UploadMappingResults Parse(HttpWebResponse response)
        {
            UploadMappingResults result = Parse<UploadMappingResults>(response);
            if (result.Mappings == null)
                result.Mappings = new Dictionary<string, string>();

            if (result.JsonObj != null)
            {
                // parsing message
                var message = result.JsonObj.Value<string>("message") ?? string.Empty;
                result.Message = message;

                // parsing mappings
                var mappingsJToken = result.JsonObj["mappings"];
                if (mappingsJToken != null)
                {
                    var mappings = mappingsJToken.Children();
                    foreach(var mapping in mappings)
                    {
                        result.Mappings.Add(mapping["folder"].ToString(), mapping["template"].ToString());
                    }
                }

                // parsing single mapping
                var folder = result.JsonObj.Value<string>("folder") ?? string.Empty;
                var template = result.JsonObj.Value<string>("template") ?? string.Empty;
                if (!string.IsNullOrEmpty(folder))
                    result.Mappings.Add(folder, template);

                //parsing NextCursor
                result.NextCursor = result.JsonObj.Value<string>("next_cursor") ?? string.Empty;
            }

            return result;
        }
Пример #26
0
        //Multiple cookies are sent as comma-separated in a single set-cookie header
        private void UpdateCookies(HttpWebResponse response)
        {
            bool cookiesTouched = false;
            for (int i = 0; i < response.Headers.Count; i++)
            {
                string name = response.Headers.GetKey(i);
                if (!name.Equals("set-cookie", StringComparison.InvariantCultureIgnoreCase))
                    continue;

                string cookieData = response.Headers.Get(i);
                if (!String.IsNullOrEmpty(cookieData))
                {
                    cookiesTouched = true;
                    cookieData += ";";
                    //Replace data formats since they contain ','
                    cookieData = Regex.Replace(cookieData, @"expires=[a-zA-Z]{2,10}\,([^;,]+[;,]{1})", "expires=$1", RegexOptions.IgnoreCase);
                    var cookies = cookieData.Split(',');
                    foreach (var strCookie in cookies)
                    {
                        var parts = strCookie.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        var nameVal = parts[0].Split('=');

                        //Update existing or create new cookie
                        Cookie cookie = new Cookie(nameVal[0], nameVal[1]);
                        foreach (var part in parts.Skip(1))
                        {
                            var keyval = part.Split('=');
                            switch (keyval[0].Trim().ToLower())
                            {
                                case "domain":
                                    cookie.Domain = keyval[1].Trim();
                                    break;
                                case "path":
                                    cookie.Path = keyval[1].Trim();
                                    break;
                                case "secure":
                                    cookie.Secure = true;
                                    break;
                                case "expires":
                                    var date = DateTime.ParseExact(keyval[1].Replace("UTC", "").Trim(), "d-MMM-yyyy HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AssumeUniversal);
                                    cookie.Expires = date.ToUniversalTime();
                                    break;
                            }
                        }

                        if (String.IsNullOrEmpty(cookie.Domain))
                        {
                            cookie.Domain = Constants.COOKIE_URI.Host;
                        }

                        _CurrentProfile.Cookies.Add(cookie);
                    }
                }
            }

            if (cookiesTouched)
            {
                _CurrentProfile.Save();
            }
        }
Пример #27
0
        private string postPaymentRequestToGateway(String queryUrl, String urlParam)
        {
            String message = "";

            try
            {
                StreamWriter myWriter   = null;                        // it will open a http connection with provided url
                WebRequest   objRequest = WebRequest.Create(queryUrl); //send data using objxmlhttp object
                objRequest.Method = "POST";
                //objRequest.ContentLength = TranRequest.Length;
                objRequest.ContentType = "application/x-www-form-urlencoded"; //to set content type
                myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(urlParam);                                     //send data
                myWriter.Close();                                             //closed the myWriter object

                // Getting Response
                System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
                using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
                {
                    message = sr.ReadToEnd();
                }
            }
            catch (Exception exception)
            {
                Console.Write("Exception occured while connection." + exception);
            }
            return(message);
        }
Пример #28
0
        public static string readfromWeb(string path)
        {
            string lcUrl = null;

            lcUrl = path;

            // *** Establish the request
            System.Net.HttpWebRequest loHttp = (HttpWebRequest)System.Net.HttpWebRequest.Create(lcUrl);

            // *** Set properties
            var timeout = 120; //seconds

            loHttp.Timeout          = timeout * 1000;
            loHttp.ReadWriteTimeout = timeout * 1000;

            loHttp.UserAgent = "Code Sample Web Client";
            Logger.WriteLine(String.Format("Downlading {0}", path));
            // *** Retrieve request info headers
            System.Net.HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();

            Encoding enc = Encoding.GetEncoding(65001);

            //Dim enc As Encoding = Encoding.GetEncoding(65001)
            //Dim enc As Encoding = Encoding.GetEncoding(1252)
            //// Windows default Code Page

            System.IO.StreamReader loResponseStream = new System.IO.StreamReader(loWebResponse.GetResponseStream(), enc);

            string lcHtml = loResponseStream.ReadToEnd();

            loWebResponse.Close();
            loResponseStream.Close();
            return(lcHtml);
        }
Пример #29
0
 public virtual string ReadResponse(HttpWebResponse response)
 {
     using (StreamReader reader = new StreamReader(response.GetResponseStream()))
     {
         return reader.ReadToEnd();
     }
 }
Пример #30
0
        public static string RemoteVersion(string url)
        {
            string rv = "";

            try
            {
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)
                                                System.Net.WebRequest.Create(url);
                System.Net.HttpWebResponse response =
                    (System.Net.HttpWebResponse)req.GetResponse();
                System.IO.Stream       receiveStream = response.GetResponseStream();
                System.IO.StreamReader readStream    =
                    new System.IO.StreamReader(receiveStream, Encoding.UTF8);
                string s = readStream.ReadToEnd();
                response.Close();
                if (ValidateFile(s))
                {
                    rv = s;
                }
            }
            catch (Exception exception)
            {
                // Anything could have happened here but
                // we don't want to stop the user
                // from using the application.
                rv = null;
                App.SendReport(exception, "Couldnt Find the Remote Version of NS");
            }
            return(rv);
        }
Пример #31
0
        public Stream GetResponseStream()
        {
            try
            {

                _webResponse = (HttpWebResponse)_webRequest.GetResponse();
                if (_webResponse.StatusCode.ToString() == ResultCode.BadRequest.ToString())
                {
                    throw (new WebException(
                        String.Format("WebException: {0} - {1}", _webResponse.StatusCode.ToString(),
                                      _webResponse.StatusDescription), new Exception(), WebExceptionStatus.ProtocolError,
                        _webResponse));
                }
                _stream = _webResponse.GetResponseStream();
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError) {
                    _webResponse = (HttpWebResponse)ex.Response;

                    _errorStream = _webResponse.GetResponseStream();
                    throw;
                }
            }

            return _stream;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WebResponseEventArgs"/> class
        /// with the specified web response.
        /// </summary>
        /// <param name="response">The HTTP web response.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="response"/> is <c>null</c>.</exception>
        public WebResponseEventArgs(HttpWebResponse response)
        {
            if (response == null)
                throw new ArgumentNullException("response");

            _response = response;
        }
        public override IODataResponseMessage EndGetResponse(IAsyncResult asyncResult)
        {
            Debug.Assert(this.httpRequest != null, "this.httpRequest != null");
            try
            {
                HttpWebResponse httpResponse = (HttpWebResponse)this.httpRequest.EndGetResponse(asyncResult);
#if PORTABLELIB
                if (!httpResponse.SupportsHeaders)
                {
                    throw new NotSupportedException(Strings.Silverlight_BrowserHttp_NotSupported);
                }
#endif
#if !ASTORIA_LIGHT
                return(new HttpWebResponseMessage(httpResponse));
#else
                System.Net.HttpWebResponse underlyingHttpResponse = httpResponse.GetUnderlyingHttpResponse();
                if (underlyingHttpResponse != null)
                {
                    return(new HttpWebResponseMessage(underlyingHttpResponse));
                }
                else
                {
                    HeaderCollection headerCollection = new HeaderCollection(httpResponse.Headers);
                    return(new HttpWebResponseMessage(headerCollection, (int)httpResponse.StatusCode, httpResponse.GetResponseStream));
                }
#endif
            }
            catch (WebException webException)
            {
                throw ConvertToDataServiceWebException(webException);
            }
        }
 /// <summary>
 /// Extracts the next visibility time from a web response header.
 /// </summary>
 /// <param name="response">The web response.</param>
 /// <returns>The time of next visibility stored in the header of the response.</returns>
 public static DateTime GetNextVisibleTime(HttpWebResponse response)
 {
     return DateTime.Parse(
         response.Headers[Constants.HeaderConstants.NextVisibleTime],
         System.Globalization.DateTimeFormatInfo.InvariantInfo,
         System.Globalization.DateTimeStyles.AdjustToUniversal);
 }
Пример #35
0
        public string GenerateMiniQR(string accessToken, string path)
        {
            string         postUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

            request.Method      = "POST";
            request.ContentType = "application/json;charset=UTF-8";

            string options = $"{{\"path\":\"{path}\"}}";

            byte[] payload = Encoding.UTF8.GetBytes(options);
            request.ContentLength = payload.Length;

            Stream writer = request.GetRequestStream();

            writer.Write(payload, 0, payload.Length);
            writer.Close();

            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream           stream   = response.GetResponseStream();
            List <byte> bytes = new List <byte>();
            int         temp  = stream.ReadByte();

            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }
            byte[] result = bytes.ToArray();
            string base64 = Convert.ToBase64String(result);//将byte[]转为base64

            return(base64);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        internal static PagSeguroServiceException CreatePagSeguroServiceException(HttpWebResponse response)
        {
            if (response == null)
                throw new PagSeguroServiceException("response answered with null value");

            if (response.StatusCode == HttpStatusCode.OK)
                throw new ArgumentException("response.StatusCode must be different than HttpStatusCode.OK", "response");

            using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
            {
                switch (response.StatusCode)
                {
                    case HttpStatusCode.BadRequest:
                        List<ServiceError> errors = new List<ServiceError>();
                        try
                        {
                            ErrorsSerializer.Read(reader, errors);
                        }
                        catch (XmlException e)
                        {
                            return new PagSeguroServiceException(response.StatusCode, e);
                        }

                        return new PagSeguroServiceException(response.StatusCode, errors);

                    default:
                        return new PagSeguroServiceException(response.StatusCode);
                }
            }
        }
Пример #37
0
        /// <summary>
        /// post数据到消息服务接口中
        /// </summary>
        /// <param name="url">消息服务地址 目前为:http://192.168.50.94:7007</param>
        /// <param name="param">post提交的json参数  示例数据:{"FromSys":"WCF","MsgType":"IM.Alert","Sender":"zhengguilong","SenderName":"郑桂 ","Target":"zhengguilong","Flag":"0","MsgId":"WCF201801280559300052","MSTitle":"数据收集任务完成通知","MSContent":"【测试新增任务】已完成收集,请到系统查看,http://192.168.50.72/Tasks/TaskInfo.aspx?taskid=cbfc8758-f133-ec8a-1346-552c2915a3d0","TargetTime":"2018-01-28 05:59:25","Priority":"3"}</param>
        /// <returns></returns>
        public static string PostToServer(string url, string param)
        {
            System.Net.HttpWebRequest request;
            request         = (System.Net.HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 10 * 1000;
            request.Method  = "POST";
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(param);
            //*******************这几行很关键
            request.ContentLength = bytes.Length;
            request.KeepAlive     = false;
            request.ServicePoint.Expect100Continue = false;
            //*******************
            Stream writer = request.GetRequestStream();

            writer.Write(bytes, 0, bytes.Length);
            writer.Close();
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream           stream   = response.GetResponseStream();
            string       line   = "";
            string       result = "";
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);

            while ((line = reader.ReadLine()) != null)
            {
                result += line + "\r\n";
            }
            return(result);
        }
Пример #38
0
        public static void CheckUpdate()
        {
            kIRCVersionChecker.Init();
            Updater = (HttpWebRequest)HttpWebRequest.Create(update_checkerurl);
            Updater_Response = (HttpWebResponse)Updater.GetResponse();

            if (Updater_Response.StatusCode == HttpStatusCode.OK)
            {
                Rocket.Unturned.Logging.Logger.Log("kIRC: Contacting updater...");
                Stream reads = Updater_Response.GetResponseStream();
                byte[] buff = new byte[10];
                reads.Read(buff, 0, 10);
                string ver = Encoding.UTF8.GetString(buff);
                ver = ver.ToLower().Trim(new[] { ' ', '\r', '\n', '\t' }).TrimEnd(new[] { '\0' });

                if (ver == VERSION.ToLower().Trim())
                {
                    Rocket.Unturned.Logging.Logger.Log("kIRC: This plugin is using the latest version!");
                }
                else
                {
                    Rocket.Unturned.Logging.Logger.LogWarning("kIRC Warning: Plugin version mismatch!");
                    Rocket.Unturned.Logging.Logger.LogWarning("Current version: "+VERSION+", Latest version on repository is " + ver + ".");
                }
            }
            else
            {
                Rocket.Unturned.Logging.Logger.LogError("kIRC Error: Failed to contact updater.");
            }
            Updater.Abort();
            Updater = null;
            Updater_Response = null;
            lastchecked = DateTime.Now;
        }
        public KiiTestHttpResponse SendRequest()
        {
            try
            {
                HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();

                KiiTestHttpResponse res = new KiiTestHttpResponse();
                // status
                res.Status = (int)httpResponse.StatusCode;
                // Etag
                res.ETag = httpResponse.Headers ["ETag"];
                // ContentType
                res.ContentType = httpResponse.ContentType;
                // read body
                res.Body = ReadBodyFromResponse(httpResponse);

                return(res);
            } catch (System.Net.WebException e)
            {
                Console.Write("Exception " + e.Message);
                System.Net.HttpWebResponse err = (System.Net.HttpWebResponse)e.Response;
                // read body
                string body = ReadBodyFromResponse(err);

                throw new KiiTestHttpException((int)err.StatusCode, body);
            }
        }
Пример #40
0
 public HttpResponse(HttpWebRequest con)
 {
     this.con = con;
     this.rsp = (HttpWebResponse)con.GetResponse();
     this.stream = rsp.GetResponseStream();
     this.reader = new StreamReader(stream, Encoding.UTF8);
 }
Пример #41
0
        public HttpResponse(HttpWebResponse httpWebResponse)
        {
            CharacterSet = httpWebResponse.CharacterSet;

            ContentEncoding = httpWebResponse.ContentEncoding;
            ContentLength = httpWebResponse.ContentLength;
            ContentType = httpWebResponse.ContentType;

            //Cookies = httpWebResponse.Cookies;
            Headers = httpWebResponse.Headers;

            //IsFromCache = httpWebResponse.IsFromCache;
            //IsMutuallyAuthenticated = httpWebResponse.IsMutuallyAuthenticated;

            //LastModified = httpWebResponse.LastModified;

            Method = httpWebResponse.Method;
            //ProtocolVersion = httpWebResponse.ProtocolVersion;

            //ResponseUri = httpWebResponse.ResponseUri;
            //Server = httpWebResponse.Server;

            HttpStatusCode = (int)httpWebResponse.StatusCode;
            StatusDescription = httpWebResponse.StatusDescription;
        }
Пример #42
0
        private PageInfo ExtractFromResponse(HttpWebResponse response)
        {
            var info = new PageInfo();

            using (var responseStream = response.GetResponseStream())
            {
                var htmlDocument = new HtmlDocument();
                htmlDocument.Load(responseStream);
                htmlDocument.OptionFixNestedTags = true;

                var quote = htmlDocument.DocumentNode
                                        .SelectSingleNode("//body")
                                        .SelectNodes("//p").Where(a => a.Attributes.Any(x => x.Name == "class" && x.Value == "qt"))
                                        .SingleOrDefault();

                var title = htmlDocument.DocumentNode
                                        .SelectSingleNode("//title");

                //Quote might not be found, bash.org doesn't have a 404 page
                if (quote == null || title == null)
                {
                    return null;
                }

                //Strip out any HTML that isn't defined in the WhiteList
                SanitizeHtml(quote);

                info.Quote = quote.InnerHtml;
                info.PageURL = response.ResponseUri.AbsoluteUri;
                info.QuoteNumber = title.InnerHtml;
            }

            return info;
        }
Пример #43
0
        public override void Handle(HttpWebResponse web_response)
        {
            string str = this.ReadResponse(ref web_response);

            if (!set_nucleus_id(str))
                throw new RequestException<WebAppPage>("Unable to find nucleus id");
        }
Пример #44
0
        public static string PostData(string strPostData)
        {
            LogHelper.WriteLog("start postData=");
            LogHelper.WriteLog(strPostData);
            LogHelper.WriteLog("end postData!");
            HttpWebRequest r = HttpWebRequest.Create(url) as HttpWebRequest;

            r.Method      = "POST";
            r.Accept      = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
            r.UserAgent   = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
            r.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            string postData = strPostData;

            byte[] data = Encoding.UTF8.GetBytes(postData);
            r.ContentLength = data.Length;
            Stream newStream = r.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            System.Net.HttpWebResponse response = r.GetResponse() as System.Net.HttpWebResponse;
            string tempresult = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();

            return(tempresult);
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="NetworkDirectWebResponse"/> class.
		/// </summary>
		/// <param name="requestUri">The request URI.</param>
		/// <param name="response">The response.</param>
		internal NetworkDirectWebResponse(Uri requestUri, HttpWebResponse response)
			: base(requestUri, response) {
			Contract.Requires<ArgumentNullException>(requestUri != null);
			Contract.Requires<ArgumentNullException>(response != null);
			this.httpWebResponse = response;
			this.responseStream = response.GetResponseStream();
		}
Пример #46
0
        public string LoginAccount(string validateCode, string user = "******", string pwd = "321123qw")
        {
            //username=wdppx123&password=e0f2714f8bf61900dcf52d80d0123915&validateCode=6126
            var password = GetMD5((GetMD5(pwd) + validateCode).ToLower());
            //   var text="username="******"&password="******"&validateCode="+validateCode;
            IDictionary <string, string> parameters = new Dictionary <string, string>
            {
                { "username", System.Web.HttpUtility.UrlEncode(user) },
                { "password", System.Web.HttpUtility.UrlEncode(password) },
                { "validateCode", System.Web.HttpUtility.UrlEncode(validateCode) }
            };

            System.Net.HttpWebResponse res = HttpRequest.Post(Settings.url.LoginURL, parameters, cookieCollection);
            if (res == null)
            {
                // debugText.Text = "未获取到post返回的消息";
                return(Settings.error.UNKNOWN);
            }
            else
            {
                cookieCollection = res.Cookies; //登录后返回的cookie
                var info = HttpRequest.GetResponseString(res);
                //  if (res.Contains("失败")) return res;
                var   rules = Settings.rules.LoginResultRules;
                Regex r     = new Regex(rules, RegexOptions.None);
                Match mc    = r.Match(info);
                var   ret   = mc.Groups[1].Value.Trim();
                return(ret);
            }
        }
        public static bool DownloadFile(Uri url, string destFileName, HttpWebResponse response, CancellationToken? token = null, Action<int> indicateProgress = null)
        {
            using (new ProfileSection("Download file", typeof(WebRequestHelper)))
              {
            ProfileSection.Argument("url", url);
            ProfileSection.Argument("destFileName", destFileName);
            ProfileSection.Argument("response", response);
            ProfileSection.Argument("token", token);
            ProfileSection.Argument("indicateProgress", indicateProgress);

            using (var responseStream = response.GetResponseStream())
            {
              try
              {
            Assert.ArgumentNotNull(responseStream, "responseStream");
            responseStream.ReadTimeout = Settings.CoreWebDownloadTimeoutMinutes.Value * Minute;
            DownloadFile(destFileName, responseStream, token, indicateProgress);

            ProfileSection.Result("Done");
            return true;
              }
              catch (OperationCanceledException)
              {
            FileSystem.FileSystem.Local.File.Delete(destFileName);

            ProfileSection.Result("Canceled");
            return false;
              }
              catch (Exception ex)
              {
            throw new InvalidOperationException("Downloading failed with exception", ex);
              }
            }
              }
        }
Пример #48
0
        public string Post(string url, Dictionary <String, String> dicList)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            request.AllowAutoRedirect         = false;
            request.AllowWriteStreamBuffering = false;
            request.Method      = "post";
            request.ContentType = "application/x-www-form-urlencoded";//"application/json";

            String postStr = buildQueryStr(dicList);

            byte[] bt = System.Text.Encoding.UTF8.GetBytes(postStr);

            request.ContentLength = bt.Length;
            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(bt, 0, bt.Length);
            stream.Close();

            try
            {
                System.Net.HttpWebResponse response       = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader     myStreamReader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"));
                var retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();

                return(retString);
            }
            catch (Exception)
            {
                return("");
            }
        }
 public void ProcessResponse(HttpWebResponse response)
 {
     foreach (var c in response.Cookies)
     {
         var cookie = c as Cookie;
         if (cookie != null)
         {
             if(cookies.ContainsKey(cookie.Name))
             {
                 cookies[cookie.Name] = cookie;
             }
             else
             {
                 cookiesLock.AcquireWriterLock(lockTimeOut);
                 try
                 {
                     cookies.Add(cookie.Name, cookie);
                 }
                 finally
                 {
                     cookiesLock.ReleaseWriterLock();
                 }
             }
         }
     }
 }
Пример #50
0
 public static CacheMetaData AddToCache(HttpWebResponse resp, string file)
 {
     string md5 = resp.Headers[HttpResponseHeader.ETag].Split(':')[0].Substring(1);
     CacheMetaData meta = new CacheMetaData(resp.ContentLength, md5.ToByteArray());
     meta.Save(file);
     return meta;
 }
Пример #51
0
        public string GetContent(HttpWebResponse webResp, Encoding encoding)
        {
            string content = null;
              var countTry = 3;
              var repeat = true;
              while (repeat && countTry > 0 && webResp != null)
            try
            {
              var responseStream = webResp.GetResponseStream();
              responseStream.ReadTimeout = 8000;
              using (var sr = new StreamReader(responseStream, encoding))
              {
            content = sr.ReadToEnd();
            webResp = null;
            if (content.Equals("обновите страницу, пожалуйста"))
              throw new WebException("ParsersChe error: Proxy no Russian");
            repeat = false;
              }
            }
            catch (WebException exWeb)
            {
              countTry--;
              content = null;
              Log(exWeb, "GetContent");
              var webReq = GetHttpWebReqNewProxy(url);
              if (webReq != null)
            webResp = GetHttpWebResp(webReq);
            }

              return content;
        }
Пример #52
0
 /// <summary>
 /// 获得企业用户余额
 /// </summary>
 /// <returns></returns>
 public int GetFee()
 {
     try
     {
         string DstUrl = string.Format("http://www.china-sms.com/send/getfee.asp?name={0}&pwd={1}", this.Name, this.Pwd);
         System.Net.HttpWebResponse rs = (System.Net.HttpWebResponse)System.Net.HttpWebRequest.Create(DstUrl).GetResponse();
         System.IO.StreamReader     sr = new System.IO.StreamReader(rs.GetResponseStream(), this.Encoding);
         this.Return = sr.ReadToEnd();
         Regex rx     = new Regex(this.GetFeeRegexPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
         Match match  = rx.Match(this.Return);
         var   retobj = new { id = 0, err = "企业用户验证失败", errid = 6010, company = "" };
         if (match.Success && match.Groups.Count == 5)
         {
             retobj = new
             {
                 id      = int.Parse(match.Groups[1].Value),
                 err     = match.Groups[2].Value,
                 errid   = int.Parse(match.Groups[3].Value),
                 company = match.Groups[4].Value
             };
         }
         return(retobj.id);
     }
     catch { return(0); }
 }
 public virtual string GetContent(HttpWebResponse webResp, Encoding encoding)
 {
     string content = null;
       var countTry = 3;
       var repeat = true;
       while (repeat && countTry > 0)
     try
     {
       var responseStream = webResp.GetResponseStream();
       responseStream.ReadTimeout = 8000;
       using (var sr = new StreamReader(responseStream, encoding))
       {
     content = sr.ReadToEnd();
     repeat = false;
       }
     }
     catch (WebException exWeb)
     {
       countTry--;
       File.AppendAllText("log.txt", exWeb.Message + Environment.NewLine);
       File.AppendAllText("log.txt", "++" + Environment.NewLine);
       File.AppendAllText("log.txt", exWeb.Status.ToString() + Environment.NewLine);
       File.AppendAllText("log.txt", "++" + Environment.NewLine);
       File.AppendAllText("log.txt", "GetContent" + Environment.NewLine);
       File.AppendAllText("log.txt", "------" + Environment.NewLine);
       var webReq = GetHttpWebReq(url);
       webResp = GetHttpWebResp(webReq);
     }
       return content;
 }
Пример #54
0
 public static System.IO.StreamReader GetWebSiteContentToStream(string url)
 {
     System.IO.StreamReader reader;
     try
     {
         //CrawlingData cData = new CrawlingData();
         string         _requestUrl   = url.Trim();
         string         _encodingType = "utf-8";
         HttpWebRequest request       = (HttpWebRequest)WebRequest.Create(_requestUrl);
         request.AllowAutoRedirect            = true;
         request.MaximumAutomaticRedirections = 3;
         request.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Arya.NET Robot)";
         request.KeepAlive = true; request.Timeout = 15 * 1000;
         System.Net.HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         //showExtractConetent.InnerHtml = ((HttpWebResponse)response).StatusDescription;
         //showExtractConetent.InnerHtml += "<br/>";
         _encodingType = GetEncodingType(response);
         reader        = new System.IO.StreamReader
                             (response.GetResponseStream(), Encoding.GetEncoding(_encodingType));
         // Read the content.
         string responseFromServer = reader.ReadToEnd();
         return(reader);
     }
     catch (WebException ex)
     {
         reader = GetWebSiteContentToStream(url);
         return(reader);
     }
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="NetworkDirectWebResponse"/> class.
		/// </summary>
		/// <param name="requestUri">The request URI.</param>
		/// <param name="response">The response.</param>
		internal NetworkDirectWebResponse(Uri requestUri, HttpWebResponse response)
			: base(requestUri, response) {
			Requires.NotNull(requestUri, "requestUri");
			Requires.NotNull(response, "response");
			this.httpWebResponse = response;
			this.responseStream = response.GetResponseStream();
		}
Пример #56
0
        protected void hlinkCreate_Click(object sender, System.EventArgs e)
        {
            string host             = this.Page.Request.Url.Host;
            string str              = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(host + "A9jkLUxm", "MD5").ToLower();
            string requestUriString = "http://wss.cnzz.com/user/companion/92hi.php?domain=" + host + "&key=" + str;

            System.Net.HttpWebRequest  httpWebRequest  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(requestUriString);
            System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
            System.IO.Stream           responseStream  = httpWebResponse.GetResponseStream();
            responseStream.ReadTimeout = 100;
            System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream);
            string text = streamReader.ReadToEnd().Trim();

            streamReader.Close();
            if (text.IndexOf("@") == -1)
            {
                this.ShowMsg("创建账号失败", false);
                return;
            }
            SiteSettings siteSettings = HiContext.Current.SiteSettings;

            string[] array = text.Split(new char[]
            {
                '@'
            });
            siteSettings.CnzzUsername = array[0];
            siteSettings.CnzzPassword = array[1];
            siteSettings.EnabledCnzz  = false;
            this.div_pan1.Visible     = false;
            this.div_pan2.Visible     = true;
            this.hplinkSet.Text       = "开启统计功能";
            SettingsManager.Save(siteSettings);
            this.ShowMsg("创建账号成功", true);
        }
 private IEnumerable<ITwitterExceptionInfo> GetStreamInfo(HttpWebResponse wexResponse)
 {
     using (var stream = wexResponse.GetResponseStream())
     {
         return GetTwitterExceptionInfosFromStream(stream);
     }
 }
        public static DateTime?GetNistTime()
        {
            DateTime?dateTime = null;

            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b");
                request.Method      = "GET";
                request.Timeout     = 3000;
                request.Accept      = "text/html, application/xhtml+xml, */*";
                request.UserAgent   = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); //No caching

                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    StreamReader stream       = new StreamReader(response.GetResponseStream());
                    string       html         = stream.ReadToEnd();//<timestamp time=\"1395772696469995\" delay=\"1395772696469995\"/>
                    string       time         = Regex.Match(html, @"(?<=\btime="")[^""]*").Value;
                    double       milliseconds = Convert.ToInt64(time) / 1000.0;
                    dateTime = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds).ToLocalTime();
                }
            }
            catch { }

            return(dateTime);
        }
Пример #59
0
 private static string ReadContentFromResult(HttpWebResponse response)
 {
     using (var reader = new StreamReader(response.GetResponseStream()))
     {
         return reader.ReadToEnd();
     }
 }
Пример #60
0
        private string getRequestObject(string urlString, string method, System.Collections.Hashtable queryStrings, bool isIncludeToken, string postBody)
        {
            if (queryStrings != null)
            {
                urlString += "?";
                foreach (string key in queryStrings.Keys)
                {
                    urlString += key + "=" + System.Web.HttpUtility.UrlEncode(queryStrings[key].ToString()) + "&";
                }
            }
            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(urlString);
            //httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method      = method;
            if (isIncludeToken)
            {
                httpWebRequest.Headers.Add("token", token);
            }
            if (!string.IsNullOrEmpty(postBody))
            {
                byte[] buf = Encoding.UTF8.GetBytes(postBody);
                httpWebRequest.ContentLength = buf.Length;
                Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(buf, 0, buf.Length);
                stream.Close();
            }
            System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
            Stream receiveStream = httpWebResponse.GetResponseStream();

            System.IO.StreamReader streamReader = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8);
            string jsonstring = streamReader.ReadToEnd();

            return(jsonstring);
        }