Close() public method

public Close ( ) : void
return void
Ejemplo n.º 1
0
        private Image DownloadImage(string pURL)
        {
            Console.WriteLine("Trying to get image : " + pURL);
            Image _tmpImage = null;

            try
            {
                System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(pURL);
                _HttpWebRequest.AllowWriteStreamBuffering = true;
                _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
                _HttpWebRequest.Referer   = "http://www.google.com/";
                _HttpWebRequest.Timeout   = 20000;
                System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();
                System.IO.Stream       _WebStream   = _WebResponse.GetResponseStream();
                _tmpImage = Image.FromStream(_WebStream);
                _WebResponse.Close();
                _WebResponse.Close();
            }
            catch (Exception _Exception)
            {
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
                return(null);
            }
            return(_tmpImage);
        }
Ejemplo n.º 2
0
        public static string Download(string url, string basePath, System.IO.FileMode openMode = System.IO.FileMode.Create, int timeout = 10000)
        {
            int counter   = 0;
            int sleepTime = 1000;

            System.Net.WebResponse response = null;
            bool error;

            do
            {
                error = false;
                counter++;
                try
                {
                    response = Download(url, timeout);
                }
                catch (WebException ex)
                {
                    error = true;
                    if (ex.Status == WebExceptionStatus.Timeout)
                    {
                        System.Threading.Thread.Sleep(sleepTime);
                        sleepTime *= 2;
                    }
                    else
                    {
                        return(ex.Message);
                    }
                }
                catch (Exception)
                {
                    error = true;
                }
            } while (error && counter < 10);

            string localPath = System.IO.Path.Combine(basePath, response.ResponseUri.Segments.Last());

            if (System.IO.File.Exists(localPath))
            {
                //todo: recursive auto file name (add 1, 2, n... after file name)
                //useful for video preview, but for a photo we can return the existing file
                response.Close();
                return(localPath);
                //throw new Exception(localPath + " already exists!");
            }
            byte[] buffer = new byte[1024];
            int    read   = 0;

            using (var fs = new System.IO.FileStream(localPath, openMode))
                using (var stream = response.GetResponseStream())
                {
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, read);
                    }
                }
            response.Close();
            return(localPath);
        }
Ejemplo n.º 3
0
        public override WebResponse GetResponse()
        {
            _syncHint = true;
            IAsyncResult result = BeginGetResponse(null, null);

            if (Timeout != Threading.Timeout.Infinite &&
                !result.IsCompleted &&
                (!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted))
            {
                _response?.Close();
                throw new WebException(SR.net_webstatus_Timeout, WebExceptionStatus.Timeout);
            }

            return(EndGetResponse(result));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string PostData(string url, string Pars, string codingName)
        {
            try
            {
                WebRequest request = WebRequest.Create(@url);
                byte[]     bs      = Encoding.UTF8.GetBytes(Pars);
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = bs.Length;
                request.Method        = "POST";

                System.IO.Stream RequestStream = request.GetRequestStream();
                RequestStream.Write(bs, 0, bs.Length);
                RequestStream.Close();

                System.Net.WebResponse response = request.GetResponse();
                StreamReader           reader   = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(codingName));
                string ReturnVal = reader.ReadToEnd();
                reader.Close();
                response.Close();

                return(ReturnVal);
            }
            catch (Exception ex)
            {
                WriteTextLog("错误", ex.ToString(), DateTime.Now);
                throw;
            }
        }
Ejemplo n.º 5
0
        private static RootObject GET(string Url, string Data)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(Url + "/" + Data);
            req.Timeout = 10000;
            //req.Proxy = CreateWebProxyWithCredentials("http://proxy.sd2.com.ua:3128", "softupdate", "271828", "Basic", "sd2.com.ua");
            req.Timeout = 100000;
            System.Net.WebResponse resp = req.GetResponse();
            //HttpWebResponse myHttpWebResponse = (HttpWebResponse)req.GetResponse();

            System.IO.Stream stream = resp.GetResponseStream();

            System.IO.StreamReader sr = new System.IO.StreamReader(stream);
            string Out = sr.ReadToEnd();

            sr.Close();

            //Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(Out);
            //var obj = JsonConvert.DeserializeObject(Out) as System.Collections.Generic.ICollection<Results>;

            var results = JsonConvert.DeserializeObject <RootObject>(Out);

            //Thread.Sleep(1000);
            req = null;
            resp.Close();
            stream.Close();
            sr = null;

            return(results);
            //return Out;
        }
Ejemplo n.º 6
0
        private Image GetImageFromHISCentral(string serviceCode)
        {
            int requestTimeout = 2000;

            try
            {
                string url = String.Format("{0}/getIcon.aspx?name={1}", _hisCentralUrl, serviceCode);
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                req.Timeout = requestTimeout;
                // Request response:
                System.Net.WebResponse webResponse = req.GetResponse();

                // Open data stream:
                System.IO.Stream webStream = webResponse.GetResponseStream();

                // convert webstream to image
                System.Drawing.Image tmpImage = System.Drawing.Image.FromStream(webStream);

                // Cleanup
                webResponse.Close();
                return(tmpImage);
            }
            catch (WebException)
            {
                //if the icon is not available on the web
                return(Properties.Resources.defaulticon);
            }
        }
Ejemplo n.º 7
0
    public static string Get_HTML(string Url)
    {
        System.Net.WebResponse Result = null;
        string Page_Source_Code;

        try
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
            Result = req.GetResponse();
            System.IO.Stream       RStream = Result.GetResponseStream();
            System.IO.StreamReader sr      = new System.IO.StreamReader(RStream);
            new System.IO.StreamReader(RStream);
            Page_Source_Code = sr.ReadToEnd();
            sr.Dispose();
        }
        catch
        {
            // error while reading the url: the url dosen’t exist, connection problem...
            Page_Source_Code = "";
        }
        finally
        {
            if (Result != null)
            {
                Result.Close();
            }
        }
        return(Page_Source_Code);
    }
Ejemplo n.º 8
0
    public long GetDownloadSizeOfBundles(List <AssetLoader.AssetBundleHash> assetBundlesToDownload)
    {
        int size = 0;

        for (int i = 0; i < assetBundlesToDownload.Count; i++)
        {
#if UNITY_ANDROID
            System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url + "Android/" + assetBundlesToDownload[i].assetBundle);
#endif
#if UNITY_IOS
            System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url + "iOS/" + assetBundlesToDownload[i].assetBundle);
#endif
            req.Method  = "HEAD";
            req.Timeout = 10000;

            int ContentLength;
            using (System.Net.WebResponse resp = req.GetResponse())
            {
                if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
                {
                    size += ContentLength;
                    //Debug.Log(assetBundlesToDownload[i].assetBundle + ", size: " + ContentLength);
                }

                resp.Close();
            }
            req.Abort();
            req = null;
            //System.GC.Collect();
        }

        return(size);
    }
Ejemplo n.º 9
0
 /// <summary>
 /// Method for sending Http post request, used to send shutdown message to dash app (interactive plot)
 /// </summary>
 /// <param name="URI"></param>
 /// <param name="Parameters"></param>
 /// <returns></returns>
 public static string HttpPost(string URI, string Parameters)
 {
     try {
         System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
         req.Proxy = WebRequest.DefaultWebProxy;
         //Add these, as we're doing a POST
         req.ContentType = "application/x-www-form-urlencoded";
         req.Method      = "POST";
         //We need to count how many bytes we're sending. Params should be name=value&
         byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
         req.ContentLength = bytes.Length;
         System.IO.Stream os = req.GetRequestStream();
         os.Write(bytes, 0, bytes.Length); //Push it out there
         os.Close();
         System.Net.WebResponse resp = req.GetResponse();
         if (resp == null)
         {
             return(null);
         }
         System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
         resp.Close();
         return(null);
     }
     catch (Exception)
     {
         return(null);
     }
 }
Ejemplo n.º 10
0
 internal bool Internet()
 {
     System.Net.WebRequest req = System.Net.WebRequest.Create("https://jbt.clsw.kr"); System.Net.WebResponse resp = default(System.Net.WebResponse); try
     { resp = req.GetResponse(); resp.Close(); req = null; return(true); }
     catch
     { req = null; return(false); }
 }
Ejemplo n.º 11
0
        private System.Drawing.Image DownloadImageFromUrl(string imageUrl)
        {
            System.Drawing.Image image = null;

            try
            {
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
                webRequest.AllowWriteStreamBuffering = true;
                webRequest.Timeout = 30000;

                System.Net.WebResponse webResponse = webRequest.GetResponse();

                System.IO.Stream stream = webResponse.GetResponseStream();

                image = System.Drawing.Image.FromStream(stream);

                webResponse.Close();
            }
            catch (Exception ex)
            {
                return(null);
            }

            return(image);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Checks to see if someone has access to a specific calendar
        /// </summary>
        /// <param name="UserName">User name</param>
        /// <param name="Password">Password</param>
        /// <param name="Directory">Directory to check</param>
        /// <param name="Server">Server location</param>
        /// <returns>true if they can, false otherwise</returns>
        public static bool HasPermissionToCalendar(string UserName, string Password, string Directory, string Server)
        {
            System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(Server + "exchange/" + Directory + "/Calendar/");

            System.Net.CredentialCache MyCredentialCache = new System.Net.CredentialCache();
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                MyCredentialCache.Add(new System.Uri(Server + "exchange/" + Directory + "/Calendar/"),
                                      "NTLM",
                                      new System.Net.NetworkCredential(UserName, Password));
            }
            else
            {
                MyCredentialCache.Add(new System.Uri(Server + "exchange/" + Directory + "/Calendar/"),
                                      "Negotiate",
                                      (System.Net.NetworkCredential)CredentialCache.DefaultCredentials);
            }

            Request.Credentials = MyCredentialCache;

            Request.Method            = "GET";
            Request.ContentType       = "text/xml; encoding='utf-8'";
            Request.UserAgent         = "Mozilla/4.0(compatible;MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)";
            Request.KeepAlive         = true;
            Request.AllowAutoRedirect = false;

            System.Net.WebResponse Response = (HttpWebResponse)Request.GetResponse();
            Response.Close();
            return(true);
        }
Ejemplo n.º 13
0
        public static string GetRequest(string url)
        {
            ILogger logger = EngineContext.Current.Resolve <ILogger>();

            try
            {
                WebRequest hr = HttpWebRequest.Create(url);
                hr.Method = "GET";
                System.Net.WebResponse response = hr.GetResponse();
                StreamReader           reader   = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                string ReturnVal = reader.ReadToEnd();
                reader.Close();
                response.Close();

                return(ReturnVal);
            }
            catch (Exception ex)
            {
                if (logger != null)
                {
                    logger.WriteErrorLog(url, ex);
                }
                return(null);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 得到文件大小
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public static string GetFileContentLength(string FilePath)
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                return(string.Empty);
            }
            string fileSize = string.Empty;
            string Path     = string.Empty;

            if (FilePath.IndexOf("http://") == -1)
            {
                Path = System.Web.HttpContext.Current.Server.MapPath(FilePath);
            }
            else
            {
                Path = FilePath;
            }
            try
            {
                System.Net.WebRequest  req = WebRequest.Create(Path);
                System.Net.WebResponse rep = req.GetResponse();
                fileSize = GetContentLength(Convert.ToInt64(rep.ContentLength));
                rep.Close();
            }
            catch { }

            return(fileSize);
        }
Ejemplo n.º 15
0
        public string GetResponse_GET(string url, Dictionary <string, string> parameters)
        {
            try
            {
                //Concatenamos los parametros, OJO: antes del primero debe estar el caracter "?"
                string parametrosConcatenados = ConcatParams(parameters);
                string urlConParametros       = url + "/" + parametrosConcatenados;

                System.Net.WebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(urlConParametros);
                wr.Method = "GET";

                wr.ContentType = "application/x-www-form-urlencoded";

                System.IO.Stream newStream;
                // Obtiene la respuesta
                System.Net.WebResponse response = wr.GetResponse();
                // Stream con el contenido recibido del servidor
                newStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(newStream);
                // Leemos el contenido
                string responseFromServer = reader.ReadToEnd();

                // Cerramos los streams
                reader.Close();
                newStream.Close();
                response.Close();
                return(responseFromServer);
            }
            catch (Exception)
            {
                throw new Exception("Not found remote service " + url);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 向服务器发送get请求,获取返回数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetWebReq(string url)
        {
            string ret = "";

            try
            {
                Random random = new Random();
                url += "&randnum=" + DateTime.Now.ToString("yyyyMMddHHmmss") + random.Next();//多加个参数避免缓存
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
                webReq.Method = "GET";
                //webReq.ContentType = "application/x-www-form-urlencoded";
                System.Net.WebResponse wResp      = webReq.GetResponse();
                System.IO.Stream       respStream = wResp.GetResponseStream();

                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.UTF8))
                {
                    ret = reader.ReadToEnd();
                }
                //lastGetTime = DateTime.Now;
                respStream.Close();
                wResp.Close();
            }
            catch (Exception e)
            {
            }
            return(ret);
        }
Ejemplo n.º 17
0
 public System.Drawing.Image DownloadImageFromUrl(string item)
 {
     System.Drawing.Image image = null;
     try
     {
         ServicePointManager.Expect100Continue = true;
         ServicePointManager.SecurityProtocol  = (SecurityProtocolType)3072;
         ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls
                                                 | SecurityProtocolType.Tls11
                                                 | SecurityProtocolType.Tls12
                                                 | SecurityProtocolType.Ssl3;
         System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)
                                                System.Net.HttpWebRequest.Create(item.Trim());
         webRequest.UseDefaultCredentials     = true;
         webRequest.Credentials               = System.Net.CredentialCache.DefaultCredentials;
         webRequest.Proxy.Credentials         = CredentialCache.DefaultCredentials;
         webRequest.AllowWriteStreamBuffering = true;
         webRequest.Timeout = 30000;
         System.Net.WebResponse webResponse = webRequest.GetResponse();
         System.IO.Stream       stream      = webResponse.GetResponseStream();
         image = System.Drawing.Image.FromStream(stream);
         webResponse.Close();
     }
     catch (Exception ex)
     {
         return(null);
     }
     return(image);
 }
Ejemplo n.º 18
0
        public string getHTML(string _URL)
        {
            string _PageContent = null;

            try
            {
                System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);

                _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";

                _HttpWebRequest.Referer = "http://www.google.com/";

                _HttpWebRequest.Timeout = 10000;

                System.Net.WebResponse _WebResponse  = _HttpWebRequest.GetResponse();
                System.IO.Stream       _WebStream    = _WebResponse.GetResponseStream();
                System.IO.StreamReader _StreamReader = new System.IO.StreamReader(_WebStream);
                _PageContent = _StreamReader.ReadToEnd();
                _StreamReader.Close();
                _WebStream.Close();
                _WebResponse.Close();
            }
            catch (Exception _Exception)
            {
                return("Exception caught in process: " + _Exception.ToString());
            }
            return(_PageContent);
        }
Ejemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        /// <param name="channel"></param>
        /// <param name="retacode"></param>
        /// <param name="transactionnum"></param>
        /// <param name="OrderID"></param>
        /// <returns></returns>
        public rerurnpram PostRestSharp(string url, string postDataStr, string channel, string retacode, string transactionnum, string OrderID)
        {
            WebRequest hr = HttpWebRequest.Create(url);

            byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(postDataStr);
            hr.ContentType   = "application/json";
            hr.ContentLength = buf.Length;
            hr.Method        = "POST";

            System.IO.Stream RequestStream = hr.GetRequestStream();
            RequestStream.Write(buf, 0, buf.Length);
            RequestStream.Close();

            System.Net.WebResponse response = hr.GetResponse();
            StreamReader           reader   = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            string ReturnVal = reader.ReadToEnd();

            reader.Close();
            response.Close();



            rerurnpram rerurnpram = new rerurnpram();

            return(rerurnpram);
        }
Ejemplo n.º 20
0
        public static Image DownloadImageFromUrl(string url)
        {
            // Create new empty image
            Image img = null;

            // Request the image through webRequest
            var webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

            webRequest.AllowWriteStreamBuffering = true;
            webRequest.Timeout = 30000;

            // Create webreponse to stream from
            System.Net.WebResponse webResponse = webRequest.GetResponse();

            // Create stream from webResponse
            Stream stream = webResponse.GetResponseStream();

            // Write stream to image
            img = Image.FromStream(stream);

            // Close webResponse
            webResponse.Close();

            // Return the new image
            return(img);
        }
Ejemplo n.º 21
0
        private void OnResponse(System.IAsyncResult result)
        {
            try
            {
                Net.HttpWebRequest request  = (Net.HttpWebRequest)result.AsyncState;
                Net.WebResponse    response = request.EndGetResponse(result);

                this.ParseTrackerResponse(response.GetResponseStream());
                response.Close();

                if (this.TrackerUpdate != null)
                {
                    this.TrackerUpdate(this.peerList, true, string.Empty);
                }

                if (this.autoUpdate && this.updateTimer == null)
                {
                    this.updateTimer = new Threading.Timer(new Threading.TimerCallback(OnUpdate), null,
                                                           this.updateInterval * 1000, this.updateInterval * 1000);
                }
            }
            catch (System.Exception e)
            {
                if (this.TrackerUpdate != null)
                {
                    this.TrackerUpdate(null, false, e.Message);
                }
                badTracker = true;
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Post 数据至服务端
        /// </summary>
        /// <param name="postContent">提交内容</param>
        /// <param name="url">提交地址</param>
        /// <returns></returns>
        public static string PostHttp(string postContent, string url)
        {
            string resultstr = string.Empty;

            System.Text.Encoding      encode = System.Text.Encoding.GetEncoding("gb2312");
            System.Net.HttpWebRequest req    = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Timeout     = 20000;
            Byte[] bytes = encode.GetBytes(postContent);
            req.ContentLength = bytes.Length;
            Stream sendStream = req.GetRequestStream();

            sendStream.Write(bytes, 0, bytes.Length);
            sendStream.Close();
            System.Net.WebResponse rep = req.GetResponse();
            Stream getStream           = rep.GetResponseStream();

            using (StreamReader sr = new StreamReader(getStream, System.Text.Encoding.UTF8))
            {
                resultstr = sr.ReadToEnd();
                sr.Close();
            }
            getStream.Close();
            rep.Close();
            return(resultstr);
        }
        //Downloads the image and returns a image object from the stream provided by the http request
        public static System.Drawing.Image DownloadImageFromUrl(string imageUrl)
        {
            System.Drawing.Image image = null;

            try
            {
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
                webRequest.AllowWriteStreamBuffering = true;
                //Timeout should probably be lower to prevent thread overload. w/e
                webRequest.Timeout = 30000;

                System.Net.WebResponse webResponse = webRequest.GetResponse();

                System.IO.Stream stream = webResponse.GetResponseStream();

                image = System.Drawing.Image.FromStream(stream);

                webResponse.Close();
            }
            //Logging in future releases~~~ XD
            catch (Exception ex)
            {
                return(null);
            }
            return(image);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="imageUrl"></param>
        /// <param name="savePath"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool DownloadImageFromUrl(string imageUrl, string savePath, out string error)
        {
            error = "";
            try
            {
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(imageUrl);
                webRequest.AllowWriteStreamBuffering = true;
                webRequest.Timeout = 30000;

                System.Net.WebResponse webResponse = webRequest.GetResponse();

                System.IO.Stream stream = webResponse.GetResponseStream();

                var image = System.Drawing.Image.FromStream(stream);

                webResponse.Close();

                var saveFolder = Path.GetDirectoryName(savePath);
                if (!Directory.Exists(saveFolder))
                {
                    Directory.CreateDirectory(saveFolder);
                }

                image.Save(savePath, ImageFormat.Jpeg);

                return(true);
            }
            catch (Exception ex)
            {
                error = ex.ToString();
                return(false);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Get the requested file size.
        /// </summary>
        /// <param name="remoteSourceFilename">The remote source file name to read data from.</param>
        /// <returns>The size of the file</returns>
        private long GetFileSize(string remoteSourceFilename)
        {
            System.Net.WebRequest  request  = null;
            System.Net.WebResponse response = null;

            try
            {
                // Create request.
                request             = System.Net.WebRequest.Create(new Uri(_remoteUri));
                request.Method      = "POST";
                request.Credentials = _networkCredential;

                // Create the request structed data.
                TextWriter textWriter = new StreamWriter(request.GetRequestStream());
                textWriter.Write(
                    "SZ".PadRight(OPERATION_STRUCTURE_BUFFER_SIZE) +
                    remoteSourceFilename.PadRight(FILENAME_STRUCTURE_BUFFER_SIZE) +
                    "0".PadRight(FILE_SIZE_STRUCTURE_BUFFER_SIZE) +
                    "0".PadRight(FILE_POSITION_STRUCTURE_BUFFER_SIZE));
                textWriter.Flush();

                // Get the response, initiate the communication
                response = request.GetResponse();

                // Get the response data from the stream
                byte[] data = new byte[response.ContentLength];
                int    ret  = response.GetResponseStream().Read(data, 0, (int)response.ContentLength);

                // If data has been returned
                if (ret > -1)
                {
                    return(Convert.ToInt64(Encoding.UTF8.GetString(data)));
                }
                else
                {
                    return(-1);
                }
            }
            catch (Exception)
            {
                return(-1);
            }
            finally
            {
                // Clean-up
                if (response != null)
                {
                    response.Close();
                }

                // Clean-up
                if (request != null)
                {
                    if (request.GetRequestStream() != null)
                    {
                        request.GetRequestStream().Close();
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public static string PostData(string Url, string RequestPara)
        {
            try
            {
                WebRequest hr = HttpWebRequest.Create(Url);

                string AppKey        = "1a129796d8af76627342fb17";
                string MasterSecret  = "2b48385bbb9f850a8ecb0344";
                string Authorization = Common.Base64Helper.EncodeBase64(AppKey + ":" + MasterSecret, "65001");

                byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
                hr.ContentType   = "application/json";
                hr.ContentLength = buf.Length;
                hr.Method        = "POST";
                hr.Headers.Add("Authorization", "Basic " + Authorization);

                System.IO.Stream RequestStream = hr.GetRequestStream();
                RequestStream.Write(buf, 0, buf.Length);
                RequestStream.Close();

                System.Net.WebResponse response = hr.GetResponse();
                StreamReader           reader   = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                string ReturnVal = reader.ReadToEnd();
                reader.Close();
                response.Close();

                return(ReturnVal);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// метод геокодирования
        /// </summary>
        /// <param name="address">адрес в формате строки</param>
        /// <returns>Возвращает широту и долготу указанного адреса</returns>
        public List <double> Geocoding(string address)
        {
            string url = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=true_or_false&language=ru", Uri.EscapeDataString(address));

            System.Net.HttpWebRequest request  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            System.Net.WebResponse    response = request.GetResponse();
            Stream       filestream            = response.GetResponseStream();
            StreamReader sreader        = new StreamReader(filestream);
            string       responsereader = sreader.ReadToEnd();

            response.Close();
            double      latitude  = 0.0;
            double      longitude = 0.0;
            XmlDocument document  = new XmlDocument();

            document.LoadXml(responsereader);
            if (document.GetElementsByTagName("status")[0].ChildNodes[0].InnerText == "OK")
            {
                XmlNodeList nodes = document.SelectNodes("//location");

                foreach (XmlNode node in nodes)
                {
                    latitude  = XmlConvert.ToDouble(node.SelectSingleNode("lat").InnerText.ToString());
                    longitude = XmlConvert.ToDouble(node.SelectSingleNode("lng").InnerText.ToString());
                }
            }
            List <double> latlng = new List <double>();

            latlng.Add(latitude);
            latlng.Add(longitude);
            return(latlng);
        }
Ejemplo n.º 28
0
        private void Button1_Click(object sender, EventArgs e)
        {
            System.Net.WebRequest  request  = null;
            System.Net.WebResponse response = null;

            string result = "";

            if (txtURL.Text != "")
            {
                string uriString = "";

                if (!txtURL.Text.StartsWith("http://"))
                {
                    uriString   = "http://" + txtURL.Text;
                    txtURL.Text = uriString;
                }
                else
                {
                    uriString = txtURL.Text;
                }

                try
                {
                    // 以WebRequest抽象類別的Create方法建立WebRequest物件
                    request = WebRequest.Create(new Uri(uriString));

                    // 設定快取原則(Cache Policy)
                    // 若有符合用戶端請求之Cache資源,則使用此Cache滿足用戶端之請求
                    // 否則將用戶端請求傳送至伺服端
                    request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);

                    // 使用WebRequest類別的GetResponse方法建立WebResponse物件
                    response = request.GetResponse();

                    // WebResponse類別之屬性

                    // 用戶端所接收資料內容的大小(byte)
                    result = result + "ContentLength: " + response.ContentLength.ToString() + "\r\n";

                    // 用戶端所接收資料內容的MIME格式
                    result = result + "ContentType: " + response.ContentType.ToString() + "\r\n";

                    // 用戶端所接收的URI
                    result = result + "ResponseUri: " + response.ResponseUri.ToString() + "\r\n";

                    // 用戶端所接收之回應內容是否從快取中取得
                    result = result + "伺服端回應是否取自Cache? " + response.IsFromCache;

                    // 關閉回應串流
                    response.Close();

                    txtResponse.Text = result;
                }
                catch (Exception ex)
                {
                    txtResponse.Text = ex.StackTrace.ToString();
                }
            }
        }
Ejemplo n.º 29
0
        public bool CheckURL(string url)
        {
            ourUri = new Uri(url);
            myWebRequest = WebRequest.Create(url);
            try
            {
                myWebResponse = myWebRequest.GetResponse();
            }
            catch
            {
                myWebResponse.Close();
                return false;

            }
            myWebResponse.Close();
            return true;
        }
Ejemplo n.º 30
0
 /// <include file='doc\TextReturnReader.uex' path='docs/doc[@for="TextReturnReader.Read"]/*' />
 public override object Read(WebResponse response, Stream responseStream) {
     try {
         string decodedString = RequestResponseUtils.ReadResponse(response);
         return matcher.Match(decodedString);
     }
     finally {
         response.Close();
     }
 }
Ejemplo n.º 31
0
        void sendThread()
        {
            log.addLog("http_get: Send Thread started");
            Uri URI = new Uri("http://" + _sHost + "/homewatch/power/index.php" + "?");

            System.Net.WebRequest  req  = null;
            System.Net.WebResponse resp = null;
            ec3k_data ec3k;

            try
            {
                while (bRunThread)
                {
                    ec3k = new ec3k_data("");
                    try
                    {
                        lock (lockQueue)
                        {
                            if (sendQueue.Count > 0)
                            {
                                ec3k = sendQueue.Dequeue();
                            } //queue count>0
                        }     //lock
                        if (ec3k._bValid)
                        {
                            string sGet = ec3k.getPostString();
                            //make the request
                            log.addLog("http_get: WEB GET=" + URI + sGet);
                            req = System.Net.WebRequest.Create(URI + sGet);
                            //req.Proxy = new System.Net.WebProxy(ProxyString, true); //true means no proxy
                            req.Timeout = 5000;
                            resp        = req.GetResponse();
                            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                            log.addLog("http_get: RESP=" + sr.ReadToEnd().Trim());
                        }//bValid
                        Thread.Sleep(1000);
                    }
                    catch (WebException ex)
                    {
                        log.addLog("http_get: WebException in sendThread(): " + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        log.addLog("http_get: web get exception: " + ex.Message);
                    }
                }
                ;
            }
            catch (Exception ex)
            {
                log.addLog("http_get: Exception in sendThread(): " + ex.Message);
            }
            try{ resp.Close(); }catch (Exception) {}
            try{ req.Abort(); }catch (Exception) {}
            log.addLog("http_get: Send Thread ended");
        }
Ejemplo n.º 32
0
		private S3Response(WebResponse response)
		{
			this.response = response;
			Stream responseStream = response.GetResponseStream();
			StreamReader streamReader = new StreamReader(responseStream);
			this.responseString = streamReader.ReadToEnd();
			streamReader.Close();
			responseStream.Close();
			response.Close();
		}
Ejemplo n.º 33
0
        private string getRandomImageURI()
        {
            System.Net.HttpWebRequest webRequest  = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(k_URLOfImagesPool);
            System.Net.WebResponse    webResponse = webRequest.GetResponse();
            string currentImageURI = webResponse.ResponseUri.ToString();

            webResponse.Close();

            return(currentImageURI);
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="response">Response of type System.Net.WebResponse</param>
 internal ExecutionResult(System.Net.WebResponse response)
 {
     this.status = ((HttpWebResponse)response).StatusDescription;
     dataStream = response.GetResponseStream();
     StreamReader reader = new StreamReader(dataStream);
     responseFromServer = reader.ReadToEnd();
     reader.Close();
     dataStream.Close();
     this.response = response;
     response.Close();
 }
Ejemplo n.º 35
0
 private void DownloadImage(WebResponse response, string url)
 {
     using (Stream stream = response.GetResponseStream())
     {
         var memoryStream = new MemoryStream();
         stream.CopyTo(memoryStream);
         var data = memoryStream.ToArray();
         AddImageCache(url, data);
     }
     response.Close();
 }
Ejemplo n.º 36
0
 private void GetdataByStates(IAsyncResult result)
 {
     response = request.EndGetResponse(result);
     StreamReader sd = new StreamReader(response.GetResponseStream());
     JsonReader jreader = new JsonTextReader(sd);
     JsonSerializer se = new JsonSerializer();
     Dictionary<string, object> GetdataState = se.Deserialize<Dictionary<string, object>>(jreader);
     dataList = DataStatebyvotes(GetdataState);
     response.Close();
     sd.Close();
     global.my_flag = 1;
 }
Ejemplo n.º 37
0
        public string[] getLyrics(String author, String songName)
        {

            string[] result = null;

            try
            {
                request = WebRequest.Create(createURL(author, songName));
                response = request.GetResponse();

                String lyrics = "";

                //now do crawling
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    doc.LoadHtml(reader.ReadToEnd());

                    lyrics = doc.DocumentNode.SelectSingleNode(Assets.DIV_NAME).InnerText;

                    foreach (HtmlNode node in doc.DocumentNode.SelectSingleNode(Assets.DIV_LYRICS).ChildNodes)
                    {
                        lyrics += node.InnerText;
                        lyrics += "\n\n";
                    }
                }

                response.Close();

                String parts = "";

                HtmlNode partnode = doc.DocumentNode.SelectSingleNode(Assets.PLUS_INFO);
                foreach (HtmlNode node in partnode.Elements(Assets.P_TAG))
                {
                    parts += node.InnerText + "\n\n";
                }

                result = new string[4];
                result[0] = doc.DocumentNode.SelectSingleNode(Assets.IMAGE_XPATH).Attributes[Assets.SRC_ATTR].Value;
                result[1] = lyrics;
                result[2] = parts;
                result[3] = "\n\nSource:Metro Lyrics";

            }
            catch
            { 
            
            }

            return result;
        }
Ejemplo n.º 38
0
 public static void CloseQuietly(WebResponse response)
 {
     try
     {
         if (response != null)
         {
             response.Close();
         }
     }
     catch (Exception ex)
     {
         log.Warn(response, ex);
     }
 }
 public override object Read(WebResponse response, Stream responseStream)
 {
     object obj2;
     try
     {
         string text = RequestResponseUtils.ReadResponse(response);
         obj2 = this.matcher.Match(text);
     }
     finally
     {
         response.Close();
     }
     return obj2;
 }
Ejemplo n.º 40
0
 public static string ParseResponseStreamToText(WebResponse response)
 {
     try
     {
         StreamReader reader = new StreamReader(response.GetResponseStream());
         
         string robotsTxt = reader.ReadToEnd();
         
         response.Close();
         reader.Close();
         
         return robotsTxt;
     }
     catch (Exception ex)
     {
         throw new Exception("An error occurred while I try to read Response Stream :(", ex);
     }
 }
Ejemplo n.º 41
0
        public bool Save( string ImagePath, string ImageURL){

            if (! Directory.Exists(ImagePath))
                Directory.CreateDirectory(ImagePath);

            string ImageName = Path.GetFileName(ImageURL);

            // Read image as byte array
            try
            {
                RequestToImage = (HttpWebRequest) WebRequest.Create(ImageURL);
                ImageResponse = RequestToImage.GetResponse();
                ResponseStream = ImageResponse.GetResponseStream();
                BinaryReader = new BinaryReader(ResponseStream);

                Image = BinaryReader.ReadBytes(500000);
            }
            catch (IOException) { MessageBox.Show("Failed to load image."); }
            finally
            {
                BinaryReader.Close();
                ResponseStream.Close();
                ImageResponse.Close();
            }
            
            // Write image to file
            FileStream = new FileStream(ImagePath + ImageName, FileMode.Create);
            BinaryWriter = new BinaryWriter(FileStream);

            try
            {
                BinaryWriter.Write(Image);
            }
            catch (IOException) { MessageBox.Show("Failed to save image."); }
            finally
            {
                FileStream.Close();
                BinaryWriter.Close();
            }

            this.ImagePath = ImagePath + ImageName;

            return File.Exists(this.ImagePath);
        }
Ejemplo n.º 42
0
        // Use this for initialization
        void Start()
        {
            //test first, need to use linq.
            request = HttpWebRequest.Create("http://io.adafruit.com/api/feeds.json");
            request.Headers.Add("X-AIO-Key", KeyManager.key);
            response = request.GetResponse();
            Debug.Log(response);
            Debug.Log(response.GetResponseStream());
            Stream data = response.GetResponseStream();
            StreamReader reader = new StreamReader(data);
            string responseFromServer = reader.ReadToEnd();
            reader.Close();
            data.Close();
            response.Close();
            Debug.Log(responseFromServer);

            ArrayList decoded = (ArrayList) JSON.JsonDecode(responseFromServer);
            Debug.Log(decoded.Count);
            Debug.Log(((Hashtable)decoded[0])["key"]);
            Feed f = new Feed((Hashtable)decoded[0]);
            Debug.Log(f.name);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Checks the file size of a remote file. If size is -1, then the file size
        /// could not be determined.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="progressKnown"></param>
        /// <returns></returns>
        private static long GetFileSize(string url)
        {
            WebResponse response = null;
            long size = -1;
            try
            {
                response = GetRequest(url).GetResponse();
                size = response.ContentLength;
            }
            finally
            {
                if (response != null)
                    response.Close();
            }

            return size;
        }
Ejemplo n.º 44
0
 private bool CheckURL()
 {
     _chkRequest = (HttpWebRequest)WebRequest.Create(_url);
     try
     {
         _chkResponse = (HttpWebResponse)_chkRequest.GetResponse();
         _chkResponse.Close();
         return true;
     }
     catch
     {
         return false;
     }
 }
        protected virtual XPathNavigator GetXpathDocumentFromResponse(WebResponse response)
        {
            using (var stream = response.GetResponseStream())
            {
                if (stream == null) throw new InvalidOperationException("Response Stream is null");

                try
                {
                    return new XPathDocument(stream).CreateNavigator();
                }
                catch (XmlException exception)
                {
                    throw new XmlException("Could not read HTTP Response as XML", exception);
                }
                finally
                {
                    response.Close();
                }
            }
        }
 public override object Read(WebResponse response, Stream responseStream)
 {
     response.Close();
     return null;
 }
Ejemplo n.º 47
0
 private void removeBT_Click(object sender, RoutedEventArgs e)   //Removes a file
 {
     try
     {
         //it is assumed that the address points to a file and not a directory
         ftpRequest = (FtpWebRequest)WebRequest.Create(address + directory + lstDir.SelectedItem.ToString());
         ftpRequest.Credentials = new NetworkCredential(c_username, c_password);
         ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         
     }
     catch
     {
         MessageBox.Show("could not delete file: " + directory);
     }
     ftpResponse.Close();
     ftpResponse = null;
     refresh(lstDir);
 }
Ejemplo n.º 48
0
 private string GetResponseContent(WebResponse response)
 {
     string content = string.Empty;
     using (var responseStream = response.GetResponseStream())
     {
         using (StreamReader reader = new StreamReader(response.GetResponseStream()))
         {
             content = reader.ReadToEnd();
         }
     }
     response.Close();
     return content;
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Parses a <see cref="WebResponse"/> containing the results of a 'getwork' request.
        /// </summary>
        /// <param name="webResponse"></param>
        /// <returns></returns>
        Work ParseGetWork(WebResponse webResponse)
        {
            // obtain and update current block number
            uint blockNumber = 0;
            if (webResponse.Headers["X-Blocknum"] != null)
                CurrentBlockNumber = blockNumber = uint.Parse(webResponse.Headers["X-Blocknum"]);

            // parse and update long poll url value if present
            var longPollUrlStr = webResponse.Headers["X-Long-Polling"];
            if (longPollUrlStr == null)
                longPollUrl = null;
            else if (longPollUrlStr == "")
                longPollUrl = url;
            else if (longPollUrlStr.StartsWith("http:") || longPollUrlStr.StartsWith("https:"))
                longPollUrl = new Uri(longPollUrlStr);
            else
                longPollUrl = new Uri(url, longPollUrlStr);

            // longPollUrl does not specify user info, but userinfo was required on initial url
            if (string.IsNullOrWhiteSpace(longPollUrl.UserInfo) && !string.IsNullOrWhiteSpace(url.UserInfo))
            {
                var b = new UriBuilder(longPollUrl);
                var u = url.UserInfo
                    .Split(':')
                    .Select(i => HttpUtility.UrlDecode(i))
                    .ToArray();
                if (u.Length >= 2)
                {
                    b.UserName = u[0];
                    b.Password = u[1];
                }
                longPollUrl = b.Uri;
            }

            // retrieve invocation response
            using (var txt = new StreamReader(webResponse.GetResponseStream()))
            using (var rdr = new JsonTextReader(txt))
            {
                if (!rdr.MoveToContent() && rdr.Read())
                    throw new JsonException("Unexpected content from 'getwork'.");

                var response = JsonConvert.Import<JsonGetWork>(rdr);
                if (response == null)
                    throw new JsonException("No response returned.");

                if (response.Error != null)
                    Console.WriteLine("JSON-RPC: {0}", response.Error);

                var result = response.Result;
                if (result == null)
                    return null;

                // decode data
                var data = Memory.Decode(result.Data);
                if (data.Length != 128)
                    throw new InvalidDataException("Received data is not valid.");

                // extract only header portion
                var header = new byte[80];
                Array.Copy(data, header, 80);

                // decode target
                var target = Memory.Decode(result.Target);
                if (target.Length != 32)
                    throw new InvalidDataException("Received target is not valid.");

                // generate new work instance
                var work = new Work()
                {
                    Pool = this,
                    BlockNumber = blockNumber,
                    Header = header,
                    Target = target,
                };

                // release connection
                webResponse.Close();

                return work;
            }
        }
Ejemplo n.º 50
0
        internal static void DisposeResponse(WebResponse wr, bool bGetStream)
        {
            if(wr == null) return;

            try
            {
                if(bGetStream)
                {
                    Stream s = wr.GetResponseStream();
                    if(s != null) s.Close();
                }
            }
            catch(Exception) { Debug.Assert(false); }

            try { wr.Close(); }
            catch(Exception) { Debug.Assert(false); }
        }
Ejemplo n.º 51
0
 /// <include file='doc\XmlReturnReader.uex' path='docs/doc[@for="XmlReturnReader.Read"]/*' />
 public override object Read(WebResponse response, Stream responseStream) {
     try {
         if (response == null) throw new ArgumentNullException("response");
         if (!ContentType.MatchesBase(response.ContentType, ContentType.TextXml)) {
             throw new InvalidOperationException(Res.GetString(Res.WebResultNotXml));
         }
         Encoding e = RequestResponseUtils.GetEncoding(response.ContentType);
         StreamReader reader = new StreamReader(responseStream, e, true);
         TraceMethod caller = Tracing.On ? new TraceMethod(this, "Read") : null;
         if (Tracing.On) Tracing.Enter(Tracing.TraceId(Res.TraceReadResponse), caller, new TraceMethod(xmlSerializer, "Deserialize", reader));
         object returnValue = xmlSerializer.Deserialize(reader);
         if (Tracing.On) Tracing.Exit(Tracing.TraceId(Res.TraceReadResponse), caller);
         return returnValue;
     }
     finally {
         response.Close();
     }
 }
Ejemplo n.º 52
0
        public void ProcessResponse(WebResponse response)
        {
            StreamReader sr = new StreamReader(response.GetResponseStream());

            if (onMessage != null && severity >= 7)
                onMessage(this,"[{0}] Reading response...",DateTime.Now);

            string data = sr.ReadToEnd ();

            response.Close ();

            Log.Write("Response: ");
            Log.WriteLine (data.ToString()+"\n");

            if (onMessage != null && severity >= 7)
                onMessage(this,"[{0}] Processing response...",DateTime.Now);

            using (JsonTextReader reader = new JsonTextReader(new StringReader(data)))
            {
            string text = "";

                Stack<string> level = new Stack<string>();
                //Stack<string> token = new Stack<string>();

                while(reader.Read())
                {
                    switch (reader.TokenClass.Name)
                    {
                        case "Member":
                            Log.Write("[{0}] {1} : ",level.Count,text = reader.Text);
                            break;
                        case "Array":
                        case "Object":
                            if (text == "")
                                Log.WriteLine("[{0}] {1} ()",level.Count,reader.TokenClass);
                            else
                                Log.WriteLine("({0})",reader.TokenClass);
                            level.Push(text);
              text = "";
                            break;
                        case "EndArray":
                        case "EndObject":
                            Log.WriteLine("[{0}] {1} ({2})",level.Count-1,reader.TokenClass,level.Pop());
                            break;
                        case "BOF":
                        case "EOF":
                            break;
                        default :
                            Log.WriteLine("{0} ({1})",reader.Text,reader.TokenClass);
                            break;
                    }
                }

                if (onMessage != null && severity >= 7)
                    onMessage(this,"[{0}] Processing complete!\n",DateTime.Now);

                if (onMessage != null && severity >= 6)
                    onMessage(this,"\n[{0}] {1} RPC call(s) remaining today",
                              DateTime.Now, cache.rpcLimit - cache.rpcCount);

                Log.WriteLine("-------------------------");
            Log.Flush();  // if we crash when we Deserialize, we still get the log!
            }

              JavaScriptSerializer js = new JavaScriptSerializer();

              r = js.Deserialize<Response>(data);

              if (r.error != null) return;

              // Cache what we need from status, if no errors
              cache.time = r.result.status.server.time;
              cache.rpcCount = r.result.status.empire.rpc_count;
              cache.rpcLimit = r.result.status.server.rpc_limit;
              cache.home_planet_id = r.result.status.empire.home_planet_id;

              // Update or add planet names to session cache
              foreach (KeyValuePair<string,string> p in r.result.status.empire.planets)
              {
            if (myColony.ContainsKey(p.Key)) {
              myColony[p.Key].name = p.Value;
            } else {
              Colony colony = new Colony(p.Key,p.Value);
              myColony.Add(p.Key,colony);
              cache.colony.Add(colony);
            }
              }
        }
Ejemplo n.º 53
0
        public override void Execute()
        {
            // fresh
            _webResponse = null;
            try
            {

                // Create a request instance
                if (_webRequest == null)
                    _webRequest = WebRequest.Create(RequestInfo.RequestUrl);

                // Initializa the instance
                InitializeWebRequest(_webRequest);

                // Post data
                ApplyPostDataToRequest(_webRequest);

                // Partial content data ranges
                ApplyContentRanges(_webRequest);

                // 0- executing plugins
                if (_isPluginAvailable)
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                        PluginMethods.IPluginWebData.BeforeExecuteGetResponse,
                        this, _webRequest);

                try
                {
                    // Get the response
                    _webResponse = _webRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    // ADDED Since V4.1:
                    // Captures unauthorized access errors.
                    // If the error isn't an unauthorized access error, then throw a relative exception.

                    WebResponse response = ex.Response;
                    if (response != null)
                    {
                        if (response is HttpWebResponse)
                        {
                            HttpWebResponse webRes = (HttpWebResponse)response;
                            if (webRes.StatusCode == HttpStatusCode.Unauthorized)
                            {

                                // Set unauthorized response data
                                FinalizeUnauthorizedWebResponse(webRes);

                                // response range
                                ReadResponseRangeInfo(webRes);

                                // Set status to normal
                                LastStatus = LastStatus.Normal;

                                // Do not continue the proccess
                                return;
                            }
                        }
                        else if (response is FtpWebResponse)
                        {
                            FtpWebResponse ftpRes = (FtpWebResponse)response;
                            if (ftpRes.StatusCode == FtpStatusCode.NotLoggedIn)
                            {
                                // Set unauthorized response data
                                FinalizeUnauthorizedWebResponse(ftpRes);

                                // response range
                                ReadResponseRangeInfo(ftpRes);

                                // Set status to normal
                                LastStatus = LastStatus.Normal;

                                // Do not continue the proccess
                                return;
                            }
                        }
                    }

                    // Nothing is captured, so throw the error
                    throw;
                }

                // 1- executing plugins
                if (_isPluginAvailable)
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                        PluginMethods.IPluginWebData.AfterExecuteGetResponse,
                        this, _webResponse);

                // Check for response persmission set from "Administration UI"
                ValidateResponse(_webResponse);

                // Response is successfull, continue to get data
                FinalizeWebResponse(_webResponse);

                // response range
                ReadResponseRangeInfo(_webResponse);

                // 2- executing plugins
                if (_isPluginAvailable)
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                        PluginMethods.IPluginWebData.AfterExecuteFinalizeWebResponse,
                        this, _webResponse);

                // Getting data
                ResponseData = ReadResponseData(_webResponse);

                // 3- executing plugins
                if (_isPluginAvailable)
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                        PluginMethods.IPluginWebData.AfterExecuteReadResponseData,
                        this);
            }
            catch (WebException ex)
            {
                // adds a special message for conenction failure
                if (ex.Status == WebExceptionStatus.ConnectFailure)
                {
                    // http status
                    if (ex.Response != null)
                    {
                        ApplyResponseHttpStatus(ex.Response);
                    }
                    else
                    {
                        ResponseInfo.HttpStatusDescription = ex.Message;
                        ResponseInfo.HttpStatusCode = (int)HttpStatusCode.NotFound;
                    }

                    ResponseInfo.ContentLength = -1;
                    LastStatus = LastStatus.Error;
                    LastException = ex;

                    // special message
                    LastErrorMessage = ex.Message +
                        "\n<br />" + "ASProxy is behind a firewall? If so, go through the proxy server or config ASProxy to pass it.";

                    return;
                }

                // ADDED 3.8.1::
                // Try to recover the request state and display original error state

                // Display original error page if requested.
                if (!RequestInfo.PrrocessErrorPage)
                    throw;

                // Continue to get data
                FinalizeWebResponse(ex.Response);

                // response range
                ReadResponseRangeInfo(ex.Response);

                // 2- executing plugins
                if (_isPluginAvailable)
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                        PluginMethods.IPluginWebData.AfterExecuteFinalizeWebResponse,
                        this, ex.Response);

                // Getting data
                ResponseData = ReadResponseData(_webResponse);

                // 3- executing plugins
                if (_isPluginAvailable)
                    Plugins.CallPluginMethod(PluginHosts.IPluginWebData,
                        PluginMethods.IPluginWebData.AfterExecuteReadResponseData,
                        this);

                // The state is error page
                LastStatus = LastStatus.ContinueWithError;
                LastException = ex;
                LastErrorMessage = ex.Message;
            }
            catch (Exception ex)
            {
                ResponseInfo.ContentLength = -1;
                LastStatus = LastStatus.Error;
                LastErrorMessage = ex.Message;
                LastException = ex;
            }
            finally
            {
                // dispose only if data is ready
                // not for streaming options
                if (RequestInfo.BufferResponse)
                    if (_webResponse != null)
                    {
                        _webResponse.Close();
                        _webResponse = null;
                    }
            }
        }
Ejemplo n.º 54
0
        /// <summary>
        /// 发送方获取接收方返回的信息
        /// </summary>
        /// <param name="res">返回给发送方的 Response 对象</param>
        /// <returns>string</returns>
        public string GetResponseStream(WebResponse res)
        {
            string strResult = "";

            Stream ResponseStream = res.GetResponseStream();
            StreamReader sr = new StreamReader(ResponseStream, Encoding.UTF8);

            Char[] read = new Char[256];

            // Read 256 charcters at a time.    
            int count = sr.Read(read, 0, 256);

            while (count > 0)
            {
                // Dump the 256 characters on a string and display the string onto the console.
                string str = new String(read, 0, count);
                strResult += str;
                count = sr.Read(read, 0, 256);
            }

            // 释放资源
            sr.Close();
            res.Close();

            return strResult;
        }
Ejemplo n.º 55
0
            public Response(WebException exception)
            {
                response = exception.Response;

                HttpWebResponse httpResponse = response as HttpWebResponse;
                if (httpResponse != null)
                {
                    StatusCode = httpResponse.StatusCode;
                    Message = httpResponse.StatusDescription;
                    ContentType = httpResponse.ContentType;

                    if (ContentType != null && ContentType.ToLower().StartsWith("text/"))
                    {
                        StringBuilder sb = new StringBuilder();

                        using (StreamReader sr = new StreamReader(httpResponse.GetResponseStream()))
                        {
                            string s;
                            while ((s = sr.ReadLine()) != null)
                            {
                                sb.Append(s);
                                sb.Append('\n');
                            }
                        }

                        ErrorContent = sb.ToString();
                    }
                }
                else
                {
                    StatusCode = HttpStatusCode.InternalServerError;
                    Message = exception.Status.ToString();
                }

                try { response.Close(); }
                catch (Exception) { }
            }
Ejemplo n.º 56
0
        //
        //refresh function
        //
        public bool refresh(ListBox listDir)
        {
            try
            {
                //create request
                ftpRequest = (FtpWebRequest)WebRequest.Create(address + directory);
                ftpRequest.Credentials = new NetworkCredential(c_username, c_password);
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpStream = ftpResponse.GetResponseStream();
                ftpReader = new StreamReader(ftpStream);
            }
            catch
            {
                MessageBox.Show("could not retrieve directory information from " + address + directory);
                return false;
            }
            // put files in listItem
            listDir.Items.Clear();
            int i = 0;
            while (ftpReader.Peek() != -1)
            {

                //read next file/directory information
                String line;
                line = ftpReader.ReadLine();

                //find the file name and add it to the listbox
                int pos = 0;
                while (line[pos++] != ':') ;
                while (line[pos++] != ' ') ;

                line.Trim();
                //Is it a directory?
                if (line[0] == 'd')
                {
                    listDir.Items.Add(line.Substring(pos) + "/");
                    isDir[i++] = true;
                }
                else
                {
                    listDir.Items.Add(line.Substring(pos));
                    isDir[i++] = false;
                }


            }

            //clear request so the refresh button may be used again
            ftpResponse.Close();
            ftpRequest = null;
            
            //update working directory
            updateDirectory();

            return true;
        }
Ejemplo n.º 57
0
        /// <summary>
        /// 读取相应消息中的流对象,将其写入指定路径
        /// </summary>
        /// <param name="response">响应消息</param>
        /// <param name="path">要写入的文件路径</param>
        private void WriteRemoteFile(WebResponse response, string path)
        {
            // 获取接收到的流
            Stream stream = response.GetResponseStream();
            // 建立一个流读取器,可以设置流编码,不设置则默认为UTF-8
            Encoding encoding = Encoding.GetEncoding("GB2312");
            System.IO.StreamReader streamReader = new StreamReader(stream, encoding);
            // 读取流字符串内容
            string content = string.Empty;
            StreamWriter streamWriter = new StreamWriter(path, false, encoding);
            try
            {
                while ((content = streamReader.ReadLine()) != null)
                {
                    // 记得readline之后此时的content中不包含换行符;
                    //streamWriter.Write(content+"\r\n");
                    // TODO:解析日志文件到对象数组中去;
                    streamWriter.Write(content+"\r\n");
                    streamWriter.Flush();

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // 资源清理代码:关闭相关对象
                streamWriter.Close();
                streamWriter.Dispose();
                streamReader.Close();
                response.Close();
            }
        }
Ejemplo n.º 58
0
 /// <summary>
 /// 获取请求的返回流
 /// </summary>
 /// <param name="res"></param>
 /// <returns></returns>
 protected string ReadResponse(WebResponse res)
 {
     string response = string.Empty;
     var stream = res.GetResponseStream();
     using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
     {
         response = reader.ReadToEnd();
     }
     res.Close();
     return response;
 }
Ejemplo n.º 59
0
        /// <summary>
        /// Retrieves the response from the request.
        /// </summary>
        /// <param name="webResponse"></param>
        /// <returns>The server response string(UTF8 decoded).</returns>
        protected virtual string RetrieveResponse(WebResponse webResponse)
        {
            var respContent = string.Empty;
            var respStream = webResponse.GetResponseStream();
            using (StreamReader reader = new StreamReader(respStream, Encoding.UTF8))
            {
                respContent = reader.ReadToEnd();
            }
            webResponse.Close();

            return respContent;
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Opens given data stream and reads the data; could be from the web, or a local file.
        /// Note that the given Response stream is closed for you before returning.
        /// </summary>
        /// <param name="Response">stream to read (closed upon completion)</param>
        /// <param name="separators">char(s) that delimit data fields</param>
        /// <param name="dataIndex">0-based index of price field of interest (open, close, etc.)</param>
        /// <returns></returns>
        private static List<decimal> GetData(WebResponse Response, char[] separators, int dataIndex)
        {
            //
            // Open data stream and download/read the data:
            //
            try
            {
                List<decimal> prices = new List<decimal>();

                using (Stream WebStream = Response.GetResponseStream())
                {
                    using (StreamReader Reader = new StreamReader(WebStream))
                    {

                        //
                        // Read data stream:
                        //
                        while (!Reader.EndOfStream)
                        {
                            string record = Reader.ReadLine();
                            string[] tokens = record.Split(separators);

                            //
                            // valid records start with a date:
                            //
                            DateTime date;
                            decimal data;

                            if (DateTime.TryParse(tokens[0], out date))
                                if (Decimal.TryParse(tokens[dataIndex], out data))
                                    prices.Add(data);
                        }//while

                    }//using--Reader
                }//using--WebStream

                //
                // return list of historical prices:
                //
                return prices;

            }
            finally
            {
                try // ensure response stream is closed before return:
                {
                    Response.Close();
                }
                catch
                { /*ignore*/ }
            }
        }