Exemplo n.º 1
0
        /// <summary>
        /// 读取一个网络文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="operateWithStream">使用网络文件流的操作</param>
        /// <param name="connectTimeoutSeconds">读取Response时的超时时间</param>
        /// <param name="maxLoadKb">最多读取的KB数</param>
        /// <returns></returns>
        public static string ReadFile(string path, Action <Stream> operateWithStream, int connectTimeoutSeconds, int maxLoadKb)
        {
            if (operateWithStream == null)
            {
                return("没有操作函数");
            }
            WebRequest  req = null;
            WebResponse res = null;

            try
            {
                req = GetRequest(path);
                if (connectTimeoutSeconds > 0)
                {
                    req.Timeout = connectTimeoutSeconds * 1000;
                }
                res = req.GetResponse();
                if (maxLoadKb > 0 && res.ContentLength > maxLoadKb * 1024)
                {
                    return("要读取的同内容过长.请检查读取长度设置或者检查文件内容!");
                }
                operateWithStream(res.GetResponseStream());
                return(string.Empty);
            }
            catch (Exception ex)
            {
                return("");
            }
            finally
            {
                res?.Close();
                req?.Abort();
            }
        }
Exemplo n.º 2
0
 public Estaciones()
 {
     InitializeComponent();
     DataContext = ViewModel;
     Loaded     += Page_Loaded;
     Unloaded   += (sender, args) =>
     {
         _httpReq?.Abort();
     };
 }
 public override void cancelAllActivities()
 {
     if (httpRequest != null)
     {
         aceLog.loger.AppendLine(" http request aborted [" + url + "]");
         httpRequest?.Abort();
     }
     else
     {
         aceLog.loger.AppendLine(" Non-http request aborted for [" + url + "]");
     }
 }
Exemplo n.º 4
0
        protected string GetContentUsingHttp(string url)
        {
            string ret = string.Empty;

#if !PocketPC
            WebRequest request = IsSocksProxy ? SocksHttpWebRequest.Create(url) : WebRequest.Create(url);
#else
            WebRequest request = WebRequest.Create(url);
#endif

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

            if (Credential != null)
            {
                request.PreAuthenticate = true;
                request.Credentials     = Credential;
            }

            if (request is HttpWebRequest)
            {
                var r = request as HttpWebRequest;
                r.UserAgent        = UserAgent;
                r.ReadWriteTimeout = TimeoutMs * 6;
                r.Accept           = requestAccept;
                r.Referer          = RefererUrl;
                r.Timeout          = TimeoutMs;
            }
#if !PocketPC
            else if (request is SocksHttpWebRequest)
            {
                var r = request as SocksHttpWebRequest;

                if (!string.IsNullOrEmpty(UserAgent))
                {
                    r.Headers.Add("User-Agent", UserAgent);
                }

                if (!string.IsNullOrEmpty(requestAccept))
                {
                    r.Headers.Add("Accept", requestAccept);
                }

                if (!string.IsNullOrEmpty(RefererUrl))
                {
                    r.Headers.Add("Referer", RefererUrl);
                }
            }
#endif
            using (var response = request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader read = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        ret = read.ReadToEnd();
                    }
                }
#if PocketPC
                request.Abort();
#endif
                response.Close();
            }

            return(ret);
        }
Exemplo n.º 5
0
        private bool GetAuthKey()
        {
            try
            {
                StringBuilder sb      = new StringBuilder();
                string        payload = "user="******",password="******"payload=" + payload;
                if (useGarena)
                {
                    payload = reToken(garenaToken);
                    query   = "payload=8393%20" + payload;
                }

                WebRequest con = WebRequest.Create(loginQueue + "login-queue/rest/queue/authenticate");
                con.Method = "POST";

                Stream outputStream = con.GetRequestStream();
                outputStream.Write(Encoding.ASCII.GetBytes(query), 0, Encoding.ASCII.GetByteCount(query));

                WebResponse webresponse = con.GetResponse();
                Stream      inputStream = webresponse.GetResponseStream();

                int c;
                while ((c = inputStream.ReadByte()) != -1)
                {
                    sb.Append((char)c);
                }

                TypedObject result = serializer.Deserialize <TypedObject>(sb.ToString());
                outputStream.Close();
                inputStream.Close();
                con.Abort();

                if (!result.ContainsKey("token"))
                {
                    int    node  = (int)result.GetInt("node");
                    string champ = result.GetString("champ");
                    int    rate  = (int)result.GetInt("rate");
                    int    delay = (int)result.GetInt("delay");

                    int id  = 0;
                    int cur = 0;

                    object[] tickers = result.GetArray("tickers");
                    foreach (object o in tickers)
                    {
                        Dictionary <string, object> to = (Dictionary <string, object>)o;

                        int tnode = (int)to["node"];
                        if (tnode != node)
                        {
                            continue;
                        }

                        id  = (int)to["id"];
                        cur = (int)to["current"];
                        break;
                    }

                    while (id - cur > rate)
                    {
                        sb.Clear();
                        if (OnLoginQueueUpdate != null)
                        {
                            OnLoginQueueUpdate(this, id - cur);
                        }

                        Thread.Sleep(delay);
                        con         = WebRequest.Create(loginQueue + "login-queue/rest/queue/ticker/" + champ);
                        con.Method  = "GET";
                        webresponse = con.GetResponse();
                        inputStream = webresponse.GetResponseStream();

                        int d;
                        while ((d = inputStream.ReadByte()) != -1)
                        {
                            sb.Append((char)d);
                        }

                        result = serializer.Deserialize <TypedObject>(sb.ToString());


                        inputStream.Close();
                        con.Abort();

                        if (result == null)
                        {
                            continue;
                        }

                        cur = HexToInt(result.GetString(node.ToString()));
                    }



                    while (sb.ToString() == null || !result.ContainsKey("token"))
                    {
                        try
                        {
                            sb.Clear();

                            if (id - cur < 0)
                            {
                                if (OnLoginQueueUpdate != null)
                                {
                                    OnLoginQueueUpdate(this, 0);
                                }
                                else
                                if (OnLoginQueueUpdate != null)
                                {
                                    OnLoginQueueUpdate(this, id - cur);
                                }
                            }

                            Thread.Sleep(delay / 10);
                            con         = WebRequest.Create(loginQueue + "login-queue/rest/queue/authToken/" + user.ToLower());
                            con.Method  = "GET";
                            webresponse = con.GetResponse();
                            inputStream = webresponse.GetResponseStream();

                            int f;
                            while ((f = inputStream.ReadByte()) != -1)
                            {
                                sb.Append((char)f);
                            }

                            result = serializer.Deserialize <TypedObject>(sb.ToString());

                            inputStream.Close();
                            con.Abort();
                        }
                        catch
                        {
                        }
                    }
                }
                if (OnLoginQueueUpdate != null)
                {
                    OnLoginQueueUpdate(this, 0);
                }
                authToken = result.GetString("token");
                userID    = result.GetString("user");

                return(true);
            }
            catch (Exception e)
            {
                if (e.Message == "The remote name could not be resolved: '" + loginQueue + "'")
                {
                    Error("Please make sure you are connected the internet!", ErrorType.AuthKey);
                    Disconnect();
                }
                else if (e.Message == "The remote server returned an error: (403) Forbidden.")
                {
                    Error("Token Expired", ErrorType.Password);
                    Disconnect();
                }
                else
                {
                    Error("Unable to get Auth Key \n" + e, ErrorType.AuthKey);
                    Disconnect();
                }

                return(false);
            }
        }
Exemplo n.º 6
0
        static void Crash()
        {
            WebRequest a = null;

            a.Abort();
        }
Exemplo n.º 7
0
        public ParsedSearch search(string showname, string searchString)
        {
            ParsedSearch ps = new ParsedSearch();

            ps.provider     = theProvider;
            ps.SearchString = searchString;
            ps.Showname     = showname;
            // request
            if (theProvider == null)
            {
                log.Error("No relation provider found/selected");
                return(ps);
            }

            string url = getSearchUrl();

            log.Debug("Search URL: " + url);
            if (string.IsNullOrEmpty(url))
            {
                log.Error("Can't search because no search URL is specified for this provider");
                return(ps);
            }
            url = url.Replace(RenamingConstants.SHOWNAME_MARKER, searchString);
            url = System.Web.HttpUtility.UrlPathEncode(url);
            log.Debug("Encoded Search URL: " + url);
            WebRequest requestHtml = null;

            try {
                requestHtml = WebRequest.Create(url);
            }
            catch (Exception ex) {
                log.Error(ex.Message);
                requestHtml?.Abort();
                return(ps);
            }
            //SetProxy(requestHtml, url);
            log.Info("Searching at " + url.Replace(" ", "%20"));
            requestHtml.Timeout = Convert.ToInt32(
                Settings.Instance.getAppConfiguration().getSingleNumberProperty(AppProperties.CONNECTION_TIMEOUT_KEY));
            // get response
            WebResponse responseHtml = null;

            try {
                responseHtml = requestHtml.GetResponse();
            }
            catch (Exception ex) {
                log.Error(ex.Message);
                responseHtml?.Close();
                requestHtml.Abort();
                return(ps);
            }
            log.Debug("Search Results URL: " + responseHtml.ResponseUri.AbsoluteUri);
            //if search engine directs us straight to the result page, skip parsing search results
            string seriesURL = getSeriesUrl();

            if (responseHtml.ResponseUri.AbsoluteUri.Contains(seriesURL))
            {
                log.Debug("Search Results URL contains Series URL: " + seriesURL);
                ps.Results = new Hashtable();
                string cleanedName = cleanSearchResultName(showname, getSearchRemove());
                if (getSearchResultsBlacklist() == "" || !Regex.Match(cleanedName, getSearchResultsBlacklist()).Success)
                {
                    ps.Results.Add(cleanedName, responseHtml.ResponseUri.AbsoluteUri + getEpisodesUrl());
                    log.Info("Search engine forwarded directly to single result: " + responseHtml.ResponseUri.AbsoluteUri.Replace(" ", "%20") + getEpisodesUrl().Replace(" ", "%20"));
                }
                return(ps);
            }
            log.Debug("Search Results URL doesn't contain Series URL: " + seriesURL + ", this is a proper search results page");
            // and download
            StreamReader r = null;

            try {
                r = new StreamReader(responseHtml.GetResponseStream());
            }
            catch (Exception ex) {
                r?.Close();
                responseHtml.Close();
                requestHtml.Abort();
                log.Error(ex.Message);
                return(ps);
            }
            string source = r.ReadToEnd();

            r.Close();

            //Source cropping
            source = source.Substring(Math.Max(source.IndexOf(getSearchStart(), StringComparison.Ordinal), 0));
            source = source.Substring(0, Math.Max(source.LastIndexOf(getSearchEnd(), StringComparison.Ordinal), source.Length - 1));
            ps     = parseSearch(ref source, responseHtml.ResponseUri.AbsoluteUri, showname, searchString);
            responseHtml.Close();
            return(ps);
        }
Exemplo n.º 8
0
        public static string DoFileRequest(string strUri, EnuHttpMethod method, string filePath, long tick = 0)
        {
            string strToRequest = strUri;

            if (tick != 0)
            {
                strToRequest += "?UpdateTicks=" + tick.ToString(CultureInfo.InvariantCulture);
            }

            WebRequest requestMsg = WebRequest.Create(strToRequest);

            MakePrincipleHeader(requestMsg, strToRequest);

            switch (method)
            {
            case EnuHttpMethod.Delete:
                requestMsg.Method = "DELETE";
                break;

            case EnuHttpMethod.Put:
            case EnuHttpMethod.Post:
                requestMsg.Method = "POST";

                break;

            default:     //EnuHttpMethod.Get:
                requestMsg.Method = "GET";
                break;
            }

            if (method == EnuHttpMethod.Post || method == EnuHttpMethod.Put)
            {
                if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
                {
                    throw new ClientException("本地文件不存在,不能读取!");
                }

                FileStream fileStream    = null;
                Stream     requestStream = null;
                try
                {
                    fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    var fileName = GetFileName(filePath);

                    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                    requestMsg.ContentType = "multipart/form-data;boundary=" + boundary;
                    requestMsg.Headers.Add("FileName", HttpUtility.UrlEncode(fileName));//额外自定义文件名放在头中
                    requestMsg.ContentLength = fileStream.Length;

                    requestStream = requestMsg.GetRequestStream();

                    byte[] buffer = new Byte[checked ((uint)Math.Min(4096,
                                                                     (int)fileStream.Length))];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }

                    fileStream.Close();
                }
                catch (Exception e)
                {
                    if (requestStream != null)
                    {
                        requestStream.Close();
                    }
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                    throw new ClientException("本地文件异常,不能读取!");
                }
            }
            else
            {
                requestMsg.ContentType = "application/json";
            }



            try
            {
                using (HttpWebResponse response = (HttpWebResponse)requestMsg.GetResponse())
                {
                    if (method == EnuHttpMethod.Post || method == EnuHttpMethod.Put)
                    {
                        //返回上传之后的文件名
                        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                        {
                            string responseFromServer = reader.ReadToEnd();
                            if (requestMsg != null)
                            {
                                requestMsg.Abort();
                            }
                            return(responseFromServer);
                        }
                    }
                    else
                    {
                        //返回文件流
                        using (Stream stream = response.GetResponseStream())
                        {
                            if (File.Exists(filePath))
                            {
                                throw new ClientException("本地文件已经存在,不能覆盖!");
                            }
                            using (FileStream fs = File.Create(filePath))
                            {
                                byte[] buffer = new byte[1024];
                                int    bytesRead;
                                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    fs.Write(buffer, 0, bytesRead);
                                }
                                fs.Close();
                            }
                        }
                        return("");
                    }
                }
            }
            catch (IOException e)
            {
                throw new ClientException("本地文件写失败!");
            }
            catch (WebException ex)
            {
                if (requestMsg != null)
                {
                    requestMsg.Abort();
                }
                var response = (HttpWebResponse)ex.Response;
                var msg      = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                throw new ClientException(msg, ex, response.StatusCode);
            }
        }
        /// <summary>
        /// Returns a response to an Internet request as an asynchronous operation.
        /// </summary>
        /// <remarks>
        /// <para>This operation will not block. The returned <see cref="Task{TResult}"/> object will
        /// complete after a response to an Internet request is available.</para>
        /// </remarks>
        /// <param name="request">The request.</param>
        /// <param name="throwOnError"><see langword="true"/> to throw a <see cref="WebException"/> if the <see cref="HttpWebResponse.StatusCode"/> of the response is greater than 400; otherwise, <see langword="false"/> to return the <see cref="WebResponse"/> in the result for these cases.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new <see cref="Task"/>.</param>
        /// <returns>A <see cref="Task"/> object which represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        /// <para>If <paramref name="request"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="WebException">
        /// <para>If <see cref="WebRequest.Abort"/> was previously called.</para>
        /// <para>-or-</para>
        /// <para>If the timeout period for the request expired.</para>
        /// <para>-or-</para>
        /// <para>If an error occurred while processing the request.</para>
        /// </exception>
        public static Task <WebResponse> GetResponseAsync(this WebRequest request, bool throwOnError, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

#if PORTABLE
            bool timeout = false;

            CancellationTokenRegistration cancellationTokenRegistration;
            if (cancellationToken.CanBeCanceled)
            {
                Action cancellationAction = request.Abort;
                cancellationTokenRegistration = cancellationToken.Register(cancellationAction);
            }
            else
            {
                cancellationTokenRegistration = default(CancellationTokenRegistration);
            }

            CancellationTokenSource noRequestTimeoutTokenSource = new CancellationTokenSource();
            WebExceptionStatus      timeoutStatus;
            if (!Enum.TryParse("Timeout", out timeoutStatus))
            {
                timeoutStatus = WebExceptionStatus.UnknownError;
            }

            int requestTimeout;
#if NET45PLUS
            try
            {
                // hack to work around PCL limitation in .NET 4.5
                dynamic dynamicRequest = request;
                requestTimeout = dynamicRequest.Timeout;
            }
            catch (RuntimeBinderException)
            {
                requestTimeout = Timeout.Infinite;
            }
#else
            // hack to work around PCL limitation in .NET 4.0
            var propertyInfo = request.GetType().GetProperty("Timeout", typeof(int));
            if (propertyInfo != null)
            {
                requestTimeout = (int)propertyInfo.GetValue(request, null);
            }
            else
            {
                requestTimeout = Timeout.Infinite;
            }
#endif

            if (requestTimeout >= 0)
            {
                Task timeoutTask = DelayedTask.Delay(TimeSpan.FromMilliseconds(requestTimeout), noRequestTimeoutTokenSource.Token).Select(
                    _ =>
                {
                    timeout = true;
                    request.Abort();
                });
            }

            TaskCompletionSource <WebResponse> completionSource = new TaskCompletionSource <WebResponse>();

            AsyncCallback completedCallback =
                result =>
            {
                try
                {
                    noRequestTimeoutTokenSource.Cancel();
                    noRequestTimeoutTokenSource.Dispose();
                    cancellationTokenRegistration.Dispose();
                    completionSource.TrySetResult(request.EndGetResponse(result));
                }
                catch (WebException ex)
                {
                    if (timeout)
                    {
                        completionSource.TrySetException(new WebException("No response was received during the time-out period for a request.", timeoutStatus));
                    }
                    else if (cancellationToken.IsCancellationRequested)
                    {
                        completionSource.TrySetCanceled();
                    }
                    else if (ex.Response != null && !throwOnError)
                    {
                        completionSource.TrySetResult(ex.Response);
                    }
                    else
                    {
                        completionSource.TrySetException(ex);
                    }
                }
                catch (Exception ex)
                {
                    completionSource.TrySetException(ex);
                }
            };

            IAsyncResult asyncResult = request.BeginGetResponse(completedCallback, null);
            return(completionSource.Task);
#else
            bool timeout = false;
            TaskCompletionSource <WebResponse> completionSource = new TaskCompletionSource <WebResponse>();

            RegisteredWaitHandle timerRegisteredWaitHandle        = null;
            RegisteredWaitHandle cancellationRegisteredWaitHandle = null;
            AsyncCallback        completedCallback =
                result =>
            {
                try
                {
                    if (cancellationRegisteredWaitHandle != null)
                    {
                        cancellationRegisteredWaitHandle.Unregister(null);
                    }

                    if (timerRegisteredWaitHandle != null)
                    {
                        timerRegisteredWaitHandle.Unregister(null);
                    }

                    completionSource.TrySetResult(request.EndGetResponse(result));
                }
                catch (WebException ex)
                {
                    if (timeout)
                    {
                        completionSource.TrySetException(new WebException("No response was received during the time-out period for a request.", WebExceptionStatus.Timeout));
                    }
                    else if (cancellationToken.IsCancellationRequested)
                    {
                        completionSource.TrySetCanceled();
                    }
                    else if (ex.Response != null && !throwOnError)
                    {
                        completionSource.TrySetResult(ex.Response);
                    }
                    else
                    {
                        completionSource.TrySetException(ex);
                    }
                }
                catch (Exception ex)
                {
                    completionSource.TrySetException(ex);
                }
            };

            IAsyncResult asyncResult = request.BeginGetResponse(completedCallback, null);
            if (!asyncResult.IsCompleted)
            {
                if (request.Timeout != Timeout.Infinite)
                {
                    WaitOrTimerCallback timedOutCallback =
                        (object state, bool timedOut) =>
                    {
                        if (timedOut)
                        {
                            timeout = true;
                            request.Abort();
                        }
                    };

                    timerRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, timedOutCallback, null, request.Timeout, true);
                }

                if (cancellationToken.CanBeCanceled)
                {
                    WaitOrTimerCallback cancelledCallback =
                        (object state, bool timedOut) =>
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            request.Abort();
                        }
                    };

                    cancellationRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(cancellationToken.WaitHandle, cancelledCallback, null, Timeout.Infinite, true);
                }
            }

            return(completionSource.Task);
#endif
        }
Exemplo n.º 10
0
        /// <summary>
        /// 获取标准北京时间,读取http://www.beijing-time.org/time.asp
        /// </summary>
        /// <returns>返回网络时间</returns>
        public static DateTime GetBeijingTime()
        {
            DateTime    dt;
            WebRequest  wrt = null;
            WebResponse wrp = null;

            try
            {
                /*
                 * String webUrl1 = "http://www.bjtime.cn";//bjTime
                 * String webUrl2 = "http://www.baidu.com";//百度
                 * String webUrl3 = "http://www.taobao.com";//淘宝
                 * String webUrl4 = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
                 * String webUrl5 = "http://www.360.cn";//360
                 * String webUrl6 = "http://www.beijing-time.org";//beijing-time /time.asp
                 */

                wrt = WebRequest.Create("http://www.baidu.com");
                wrp = wrt.GetResponse();

                DateTime dt1 = GetStandardTime();

                string html = string.Empty;
                using (Stream stream = wrp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        html = sr.ReadToEnd();
                    }
                }

                string[] tempArray = html.Split(';');
                for (int i = 0; i < tempArray.Length; i++)
                {
                    tempArray[i] = tempArray[i].Replace("\r\n", "");
                }

                string year   = tempArray[1].Split('=')[1];
                string month  = tempArray[2].Split('=')[1];
                string day    = tempArray[3].Split('=')[1];
                string hour   = tempArray[5].Split('=')[1];
                string minite = tempArray[6].Split('=')[1];
                string second = tempArray[7].Split('=')[1];

                dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second);
            }
            catch (WebException ex)
            {
                return(DateTime.Parse("2011-1-1"));
            }
            catch (Exception ex)
            {
                return(DateTime.Parse("2011-1-1"));
            }
            finally
            {
                if (wrp != null)
                {
                    wrp.Close();
                }
                if (wrt != null)
                {
                    wrt.Abort();
                }
            }
            return(dt);
        }
Exemplo n.º 11
0
 public void Dispose()
 {
     base.Dispose();
     _webRequest.Abort();
 }
Exemplo n.º 12
0
        static IEnumerable <Task> _getResponseAsync(TaskCompletionSource <WebResponse> tcs, WebRequest request, TimeSpan timeout)
        {
            using (var cancellation_token = new Concurrency.TimeoutToken(timeout))
                using (var registration_token = cancellation_token.Token.Register(() => { request.Abort(); }))
                {
                    using (var task_get_response = request.GetResponseAsync())
                    {
                        yield return(task_get_response);

                        tcs.SetFromTask(task_get_response);
                        yield break;
                    }
                }
        }
Exemplo n.º 13
0
 /// <summary>
 /// Cancel the query if it is running. This invalidates the object, which
 /// should not be reused after that.
 /// </summary>
 public void Cancel()
 {
     m_stopped = true;
     m_query.Abort();
 }
Exemplo n.º 14
0
        private static void SecondLayer(string link, bool debugmode, int retrytimes)
        {
            byte[] buffer = null;
            NewWebClient webclient = new NewWebClient(60*1000);
            string currenthtml = "";
            string title = "";
            string htmlbackup = "";
            if (debugmode)
            {
                string filepath = "D:\\page2.txt";
                currenthtml = LocalFileReader(filepath);
            }
            else
            {
                try
                {
                    buffer = webclient.DownloadData(link);
                    currenthtml = Encoding.GetEncoding("gbk").GetString(buffer);
                }
                catch
                {
                    if (retrytimes < 5)
                        SecondLayer(link, debugmode, retrytimes++);
                    else
                        return;
                }
            }
            //Get the title
            Match titlematch = new Regex("(?<=<meta name=\"description\" content=\")[\\s\\S]*(?= 草榴社區 t66y\\.com\" />)").Match(currenthtml);
            title = titlematch.Value;
            title = title.Replace("/", "_");
            title = title.Replace("[", "_");
            title = title.Replace("]", "_");
            title = title.Replace("\\", "");
            title = title.Replace("?", "");
            title = title.Replace("*", "");

            //Get rid of  all the Quotes
            htmlbackup = currenthtml;
            Match match1 = new Regex("<br><h6 class=\"quote\">Quote:</h6><blockquote>[\\s\\S]*</blockquote><br>").Match(currenthtml);
            if (match1.Value != "")
                currenthtml = currenthtml.Replace(match1.Value, "");

            //Get all the images
            MatchCollection matchjpg = new Regex("(?<=ess-data=')((?!ess-data=')[\\s\\S])*?\\.(jpg|png)(?='>)").Matches(currenthtml);
            //Very interesting ((?!xxx).) is a good trick
            if (matchjpg.Count == 0)
            {
                currenthtml = htmlbackup;
                matchjpg = new Regex("(?<=ess-data=')((?!ess-data=')[\\s\\S])*?\\.(jpg|png)(?='>)").Matches(currenthtml);
            }
            string imgfilename = "";
            string filedictory = "d:\\my t66y\\" + title + "\\";
            if (!Directory.Exists(filedictory))
                Directory.CreateDirectory(filedictory);
            
            for (int i = 0; i < matchjpg.Count; i++)
            {
                match1 = new Regex("(?<=/)((?!/).)+\\.(jpg|png)").Match(matchjpg[i].Value);
                imgfilename = match1.Value;
                try
                {
                    string _path = "d:\\my t66y\\" + title + "\\" + imgfilename;
                    if (!File.Exists(_path))
                        webclient.DownloadFile(new Uri(matchjpg[i].Value), _path);
                }
                catch (WebException wb)
                {
                    if (wb.Status == WebExceptionStatus.Timeout)
                    {

                    }
                    if (i > matchjpg.Count / 2)
                        continue;
                    else
                        if (retrytimes < 5)
                        SecondLayer(link, debugmode, retrytimes++);
                    else
                        return;
                }
            }
            

            //Get download link
            match1 = new Regex("http://www\\.rmdown\\.com/[\\s\\S]*?(?=</a>)").Match(currenthtml);
            string downloadlink = match1.Value;

            if (downloadlink != "")
            {
                string hashlink = new Regex("(?<=http://www\\.rmdown\\.com/link\\.php\\?hash=)[\\s\\S]*").Match(downloadlink).Value;
                /*
                string filename = filedictory + "downloadlink.txt";
                FileStream myfile = new FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                StreamWriter sw = new StreamWriter(myfile, System.Text.Encoding.Default);
                sw.WriteLine(downloadlink);
                sw.Close();
                myfile.Close();
                */
                //webclient.Headers.Add("GET ",hashlink);
                webclient.Headers.Add("Referer",downloadlink);
                webclient.Headers.Add("Cookie", "__cfduid=de6459d21de4fe09c8cf6754f71bbae1a1584457144");

                string torrentslink = "http://www.rmdown.com/download.php?reff=110&ref="+hashlink;
                WebRequest myrequest = WebRequest.Create(downloadlink);
                myrequest.Timeout = 30 * 1000;
                if (!File.Exists(filedictory + "downloadlink.txt"))
                    LocalFileWriter(filedictory + "downloadlink.txt", downloadlink);
                //myrequest.GetResponse();
                try
                {
                    string _path = "d:\\my t66y\\" + title + "\\" + "torrent.torrent";
                    if (!File.Exists(_path))
                    {
                        string password = myrequest.GetResponse().Headers["Set-Cookie"];
                        /*
                        buffer = webclient.DownloadData(downloadlink);

                        string t = Encoding.GetEncoding("utf-8").GetString(buffer);
                        string password = webclient.ResponseHeaders["Set-Cookie"];
                        */
                        password = password.Replace("; path=/", "");
                        //webclient.Headers["Cookie"]="__cfduid=de6459d21de4fe09c8cf6754f71bbae1a1584457144;"+password+";";
                        password = new Regex("PHPSESSID=[\\s\\S]*").Match(password).Value;
                        //webclient.Headers["Cookie"] = password;
                        webclient.Headers["Cookie"] = "__cfduid=de6459d21de4fe09c8cf6754f71bbae1a1584457144;" + password + ";";
                        try
                        {
                            if (!File.Exists(_path))
                                webclient.DownloadFile(torrentslink, _path);
                        }
                        catch (WebException wb)
                        {
                            return;
                        }
                    }    
                }
                catch (WebException wb)
                {
                    myrequest.Abort();
                    return;
                }
                Console.WriteLine();
            }
            Console.WriteLine();
            //Get the download link
        }
Exemplo n.º 15
0
 public void Abort()
 {
     _webRequest.Abort();
 }
Exemplo n.º 16
0
        protected PureImage GetTileImageUsingHttp(string url)
        {
            // URLに対するアクセス回数保存用処理ここから
            // 現在日付取得

            DateTime dtNow = DateTime.Now;

            if (dtNow.ToString("yyyy/MM/dd") != strUrlCountDate)
            {
                // 日付が異なる場合
                strUrlCountDate = dtNow.ToString("yyyy/MM/dd");
                dicUrlCount.Clear();
            }

            Uri u = new Uri(url);

            if (dicUrlCount.ContainsKey(u.Host))
            {
                // キーが存在する場合
                int i = dicUrlCount[u.Host];
                i++;
                dicUrlCount[u.Host] = i;
            }
            else
            {
                // キーが存在しない場合
                dicUrlCount[u.Host] = 1;
            }
            // URLに対するアクセス回数保存用処理ここまで

            PureImage ret = null;

#if !PocketPC
            WebRequest request = IsSocksProxy ? SocksHttpWebRequest.Create(url) : WebRequest.Create(url);
#else
            WebRequest request = WebRequest.Create(url);
#endif
            if (WebProxy != null)
            {
                request.Proxy = WebProxy;
            }

            if (Credential != null)
            {
                request.PreAuthenticate = true;
                request.Credentials     = Credential;
            }

            if (request is HttpWebRequest)
            {
                var r = request as HttpWebRequest;
                r.UserAgent        = UserAgent;
                r.ReadWriteTimeout = TimeoutMs * 6;
                r.Accept           = requestAccept;
                r.Referer          = RefererUrl;
                r.Timeout          = TimeoutMs;
            }
#if !PocketPC
            else if (request is SocksHttpWebRequest)
            {
                var r = request as SocksHttpWebRequest;

                if (!string.IsNullOrEmpty(UserAgent))
                {
                    r.Headers.Add("User-Agent", UserAgent);
                }

                if (!string.IsNullOrEmpty(requestAccept))
                {
                    r.Headers.Add("Accept", requestAccept);
                }

                if (!string.IsNullOrEmpty(RefererUrl))
                {
                    r.Headers.Add("Referer", RefererUrl);
                }
            }
#endif
            using (var response = request.GetResponse())
            {
                if (CheckTileImageHttpResponse(response))
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        MemoryStream data = Stuff.CopyStream(responseStream, false);

                        Debug.WriteLine("Response[" + data.Length + " bytes]: " + url);

                        if (data.Length > 0)
                        {
                            ret = TileImageProxy.FromStream(data);

                            if (ret != null)
                            {
                                ret.Data          = data;
                                ret.Data.Position = 0;
                            }
                            else
                            {
                                data.Dispose();
                            }
                        }
                        data = null;
                    }
                }
                else
                {
                    Debug.WriteLine("CheckTileImageHttpResponse[false]: " + url);
                }
#if PocketPC
                request.Abort();
#endif
                response.Close();
            }
            return(ret);
        }
Exemplo n.º 17
0
    private void SubscribeThread(string channel, stringCallback theCallback)
    {
        string     output      = "";
        string     queryString = "";
        string     timeToken   = "0";
        WebRequest objRequest  = null;

        Debug.Log("Thread " + channel + " started");

        while (!stopped && threadPool.ContainsKey(channel))
        {
            try
            {
                // Create the Query URL
                queryString = "subscribe/" + pubnubSubKey + "/" + channel + "/0/" + timeToken;

                WebClient client = new MyWebClient();
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                Stream       data   = client.OpenRead(PubnubURL + queryString);
                StreamReader reader = new StreamReader(data);
                output = reader.ReadToEnd();
                data.Close();
                reader.Close();

                // Convert it to a form we can work with, namely an Array with the first element an Array of messages
                // And the second element the timeToken
                ArrayList outputArray = (ArrayList)JSON.JsonDecode(output);
                if (outputArray != null)
                {
                    // The timeToken, used to make sure we get new messages next time around
                    timeToken = (string)outputArray[1];

                    // The messages
                    ArrayList messageArray = (ArrayList)outputArray[0];

                    // Call the Callback function for each message, turning it into text on the way if necessary
                    foreach (object message in messageArray)
                    {
                        if (message is string)
                        {
                            theCallback((string)message);
                        }
                        else if ((message is Hashtable) || (message is ArrayList))
                        {
                            theCallback(JSON.JsonEncode(message));
                        }
                        else // Probably a number
                        {
                            theCallback(message.ToString());
                        }
                    }
                }
            }
            catch (WebException w)
            {
                if (objRequest != null)
                {
                    objRequest.Abort();
                }
            }
            catch (ThreadAbortException a)
            {
                if (objRequest != null)
                {
                    objRequest.Abort();
                }
            }
            catch (ThreadInterruptedException i)
            {
                if (objRequest != null)
                {
                    objRequest.Abort();
                }
            }
            catch (Exception e)
            {
                if (objRequest != null)
                {
                    objRequest.Abort();
                }
            }

            // Give some other threads a chance
            Thread.Sleep(100);
        }

        if (objRequest != null)
        {
            objRequest.Abort();
        }
        Debug.Log("Thread " + channel + " stopped");
    }
Exemplo n.º 18
0
 public void PingAbort()
 {
     requestPingAborting = true;
     requestPing.Abort();         //cancel an asynchronous request
 }
Exemplo n.º 19
0
        private void DownLoadFile()
        {
            // 测试使用
            //string fileFullpath = "http://localhost:29700//UpLoadFile";
            string fileFullpath = Helper.ServerFilePath;
            // 获得DataGridView选中行
            DataGridViewRow selectedRow = this.dgvFiles.SelectedRows[0];
            string          fileName    = selectedRow.Cells[0].Value.ToString(); // 文件名称

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.InitialDirectory = "C:";
            sfd.FileName         = fileName;
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileFullpath += string.Format("//{0}", fileName);
                if (txtDownLoadPath.InvokeRequired)
                {
                    txtDownLoadPath.Invoke((ThreadStart) delegate
                    {
                        this.txtDownLoadPath.Text = sfd.FileName;
                    });
                }

                WebRequest  request = WebRequest.Create(fileFullpath);
                WebResponse fs      = null;
                try
                {
                    fs = request.GetResponse();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "/r/n请确保文件名不存在特殊字符");
                }
                long contentLength = fs.ContentLength;
                if (pbDownLoad.InvokeRequired)
                {
                    pbDownLoad.Invoke((ThreadStart) delegate
                    {
                        pbDownLoad.Maximum = (int)contentLength;
                    });
                }
                Stream st = fs.GetResponseStream();
                try
                {
                    byte[] byteLength = new byte[contentLength];
                    int    allByte    = (int)contentLength;
                    int    startByte  = 0;
                    while (contentLength > 0)
                    {
                        int downByte = st.Read(byteLength, startByte, allByte);
                        if (downByte == 0)
                        {
                            break;
                        }
                        startByte += downByte;
                        // 计算下载进度
                        //int percent = (int)(((double)startByte / ((long)(double)allByte)) * 100);
                        //(sender as BackgroundWorker).ReportProgress(percent);
                        if (pbDownLoad.InvokeRequired)
                        {
                            pbDownLoad.Invoke((ThreadStart) delegate
                            {
                                pbDownLoad.Value = startByte;
                            });
                        }
                        allByte -= downByte;
                    }
                    // 保存路径
                    string     downLoadPath = sfd.FileName;
                    FileStream stream       = new FileStream(downLoadPath, FileMode.OpenOrCreate, FileAccess.Write);
                    stream.Write(byteLength, 0, byteLength.Length);
                    stream.Close();
                    fs.Close();
                    Thread.Sleep(500);
                    MessageBox.Show("下载成功");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    st.Close();
                    st.Dispose();
                    request.Abort();

                    if (pbDownLoad.InvokeRequired)
                    {
                        pbDownLoad.Invoke((ThreadStart) delegate
                        {
                            pbDownLoad.Maximum = 0;
                        });
                    }
                }
            }
            #endregion
        }
Exemplo n.º 20
0
 protected void FetchTwitts()
 {
     try
     {
         string dt = DateTime.Now.ToString();
         TwitterSettingsInfo twtData = new TwitterSettingsInfo();
         TwitterSqlhandler   twtSql  = new TwitterSqlhandler();
         int  userModuleID;
         bool status = int.TryParse(SageUserModuleID, out userModuleID);
         twtData = twtSql.GetTwitterSettingValues(userModuleID, GetPortalID);
         string title = string.Empty;
         title = twtData.Title;
         string      screenName = twtData.ScreenName.ToString();
         int         count      = twtData.Count;
         string      twtUrl     = string.Format(twitterUrl, screenName, count);
         WebRequest  reqTwitts  = WebRequest.Create(twtUrl);
         WebResponse twtResp    = reqTwitts.GetResponse();
         if (twtResp != null)
         {
             XmlDocument twtXdoc = new XmlDocument();
             twtXdoc.Load(twtResp.GetResponseStream());
             twtResp.Close();
             reqTwitts.Abort();
             XmlElement    root            = twtXdoc.DocumentElement;
             XmlNodeList   nodes           = root.SelectNodes("/statuses/status");
             StringBuilder strTwittsViewer = new StringBuilder();
             strTwittsViewer.Append("<h2>" + title + "</h2>");
             foreach (XmlNode node in nodes)
             {
                 DateTime diffDate = DateTime.ParseExact(node["created_at"].InnerText, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
                 strTwittsViewer.Append("<p>");
                 strTwittsViewer.Append(ConvertUrlsToLinks(node["text"].InnerText));
                 strTwittsViewer.Append("<span> about ");
                 TimeSpan ts = DateTime.Now - diffDate;
                 if (ts.Days > 0)
                 {
                     strTwittsViewer.Append(ts.Days);
                     strTwittsViewer.Append(" days ago");
                 }
                 else if (ts.Hours > 0)
                 {
                     strTwittsViewer.Append(ts.Hours);
                     strTwittsViewer.Append(" hours ago");
                 }
                 else if (ts.Minutes > 0)
                 {
                     strTwittsViewer.Append(ts.Minutes);
                     strTwittsViewer.Append(" minutes ago");
                 }
                 else
                 {
                     strTwittsViewer.Append(ts.Seconds);
                     strTwittsViewer.Append(" seconds ago");
                 }
                 strTwittsViewer.Append(" via </span>");
                 strTwittsViewer.Append(node["source"].InnerText);
                 strTwittsViewer.Append("</p>");
             }
             ltrlTwitts.Text = strTwittsViewer.ToString();
         }
     }
     catch
     {
     }
 }
Exemplo n.º 21
0
        private string RequestOtherAPI(string method, string url, string authHeader, string contentType, string data = null)
        {
            string content = null;

            WebRequest      webRequest   = null;
            WebResponse     webResponse  = null;
            HttpWebResponse httpResponse = null;
            Stream          dataStream   = null;
            StreamReader    streamReader = null;

            try
            {
                webRequest             = WebRequest.Create(url);
                webRequest.Method      = method;
                webRequest.ContentType = contentType;
                webRequest.Headers.Add(HttpRequestHeader.Authorization, authHeader);

                // If there is data to send,
                // do appropriate logic
                if (!string.IsNullOrEmpty(data))
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(data);
                    webRequest.ContentLength = byteArray.Length;
                    dataStream = webRequest.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
                }

                webResponse = webRequest.GetResponse();

                httpResponse = (HttpWebResponse)webResponse;

                dataStream = webResponse.GetResponseStream();

                streamReader = new StreamReader(dataStream);

                content = streamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                return("");
            }
            finally
            {
                if (streamReader != null)
                {
                    streamReader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                if (httpResponse != null)
                {
                    httpResponse.Close();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                }
                if (webRequest != null)
                {
                    webRequest.Abort();
                }
            }

            return(content);
        }
Exemplo n.º 22
0
        public void Start()
        {
            if (StreamState == StreamState.Stop && !_isNew)
            {
                return;
            }

            this.Raise(StreamStarted);
            SetStreamState(StreamState.Resume);

            _currentWebRequest   = _generateWebRequest();
            _currentStreamReader = CreateStreamReaderFromWebRequest(_currentWebRequest);

            int numberOfRepeatedFailures = 0;

            while (StreamState != StreamState.Stop)
            {
                if (StreamState == StreamState.Pause)
                {
                    using (EventWaitHandle tmpEvent = new ManualResetEvent(false))
                    {
                        tmpEvent.WaitOne(TimeSpan.FromSeconds(STREAM_RESUME_DELAY));
                    }

                    continue;
                }

                try
                {
                    var jsonResponse = GetJsonResponseFromReader();

                    var isJsonResponseValid = jsonResponse != null;
                    if (!isJsonResponseValid)
                    {
                        if (TryHandleInvalidResponse(numberOfRepeatedFailures))
                        {
                            ++numberOfRepeatedFailures;
                            continue;
                        }

                        break;
                    }

                    numberOfRepeatedFailures = 0;

                    if (jsonResponse == string.Empty)
                    {
                        continue;
                    }

                    if (StreamState == StreamState.Resume && !_processObject(jsonResponse))
                    {
                        SetStreamState(StreamState.Stop);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (!ShouldContinueAfterHandlingException(ex))
                    {
                        SetStreamState(StreamState.Stop);
                        break;
                    }
                }
            }

            if (_currentWebRequest != null)
            {
                _currentWebRequest.Abort();
            }

            if (_currentStreamReader != null)
            {
                _currentStreamReader.Dispose();
            }
        }
Exemplo n.º 23
0
        private void getSecretBG_DoWork(object sender, DoWorkEventArgs e)
        {
            getSecretBG.WorkerSupportsCancellation = true;

            WebClient bundleURLClient = new WebClient();
            string    bundleHTML      = bundleURLClient.DownloadString("https://play.qobuz.com/login");

            // Grab link to bundle.js
            var bundleLog    = Regex.Match(bundleHTML, "<script src=\"(?<bundleJS>\\/resources\\/\\d+\\.\\d+\\.\\d+-[a-z]\\d{3}\\/bundle\\.js)").Groups;
            var bundleSuffix = bundleLog[1].Value;
            var bundleURL    = "https://play.qobuz.com" + bundleSuffix;

            WebRequest bundleWR = WebRequest.Create(bundleURL);

            try
            {
                WebResponse  bundleWS = bundleWR.GetResponse();
                StreamReader bundleSR = new StreamReader(bundleWS.GetResponseStream());

                string getBundleRequest = bundleSR.ReadToEnd();
                string text             = getBundleRequest;

                // Grab app_id from bundle.js
                var bundleLog0 = Regex.Match(getBundleRequest, "\\):\\(n.qobuzapi={app_id:\"(?<appID>.*?)\",app_secret:").Groups;
                appID = bundleLog0[1].Value;

                // Grab "info" and "extras"
                var bundleLog1   = Regex.Match(getBundleRequest, "{offset:\"(?<notUsed>.*?)\",name:\"Europe\\/Berlin\",info:\"(?<info>.*?)\",extras:\"(?<extras>.*?)\"}").Groups;
                var bundleInfo   = bundleLog1[2].Value;
                var bundleExtras = bundleLog1[3].Value;

                // Grab "seed"
                var bundleLog2 = Regex.Match(getBundleRequest, "window.utimezone.paris\\):h.initialSeed\\(\"(?<seed>.*?)\",window.utimezone.berlin\\)").Groups;
                var bundleSeed = bundleLog2[1].Value;

                // Step 1 of getting the app_secret
                string B64step1 = bundleSeed + bundleInfo + bundleExtras;
                B64step1 = B64step1.Remove(B64step1.Length - 44, 44);
                byte[] step1Bytes = Encoding.UTF8.GetBytes(B64step1);
                B64step1 = Convert.ToBase64String(step1Bytes);

                // Step 2 of getting the app_secret
                byte[] step2Data = Convert.FromBase64String(B64step1);
                string B64step2  = Encoding.UTF8.GetString(step2Data);

                // Step 3 of getting the app_secret
                byte[] step3Data = Convert.FromBase64String(B64step2);

                // Set app_secret
                appSecret = Encoding.UTF8.GetString(step3Data);
                loginText.Invoke(new Action(() => loginText.Text = "ID and Secret Obtained! Logging in.."));
                System.Threading.Thread.Sleep(1000);
            }
            catch (Exception bundleEx)
            {
                // If obtaining bundle.js info fails, show error info.
                string bundleError = bundleEx.ToString();
                loginText.Invoke(new Action(() => loginText.Text = "Couldn't obtain app info. Error Log saved"));
                System.IO.File.WriteAllText(errorLog, bundleError);
                bundleWR.Abort();
                loginButton.Invoke(new Action(() => loginButton.Enabled     = true));
                altLoginLabel.Invoke(new Action(() => altLoginLabel.Visible = true));
                return;
            }

            bundleWR.Abort();

            if (altLoginValue == "0")
            {
                loginBG.RunWorkerAsync();
            }
            else if (altLoginValue == "1")
            {
                altLoginBG.RunWorkerAsync();
            }
            getSecretBG.CancelAsync();
        }
Exemplo n.º 24
0
        protected PureImage GetTileImageUsingHttp(string url)
        {
            PureImage ret = null;

#if !PocketPC
            WebRequest request = IsSocksProxy ? SocksHttpWebRequest.Create(url) : WebRequest.Create(url);
#else
            WebRequest request = WebRequest.Create(url);
#endif
            if (WebProxy != null)
            {
                request.Proxy = WebProxy;
            }

            if (Credential != null)
            {
                request.PreAuthenticate = true;
                request.Credentials     = Credential;
            }

            if (request is HttpWebRequest)
            {
                var r = request as HttpWebRequest;
                r.UserAgent        = UserAgent;
                r.ReadWriteTimeout = TimeoutMs * 6;
                r.Accept           = requestAccept;
                r.Referer          = RefererUrl;
                r.Timeout          = TimeoutMs;
            }

            using (var response = request.GetResponse())
            {
                if (CheckTileImageHttpResponse(response))
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        MemoryStream data = Stuff.CopyStream(responseStream, false);


                        if (data.Length > 0)
                        {
                            ret = TileImageProxy.FromStream(data);

                            if (ret != null)
                            {
                                ret.Data          = data;
                                ret.Data.Position = 0;
                            }
                            else
                            {
                                data.Dispose();
                            }
                        }
                        data = null;
                    }
                }
                else
                {
                }
#if PocketPC
                request.Abort();
#endif
                response.Close();
            }
            return(ret);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 获取北京时间
        /// </summary>
        /// <returns></returns>
        private static DateTime getTime()
        {
            //t0 = new Date().getTime();
            //nyear = 2011;
            //nmonth = 7;
            //nday = 5;
            //nwday = 2;
            //nhrs = 17;
            //nmin = 12;
            //nsec = 12;
            DateTime    dt;
            WebRequest  wrt = null;
            WebResponse wrp = null;

            try
            {
                wrt = WebRequest.Create("http://www.beijing-time.org/time.asp");
                wrp = wrt.GetResponse();

                string html = string.Empty;
                using (Stream stream = wrp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        html = sr.ReadToEnd();
                    }
                }

                string[] tempArray = html.Split(';');
                for (int i = 0; i < tempArray.Length; i++)
                {
                    tempArray[i] = tempArray[i].Replace("\r\n", "");
                }

                string year   = tempArray[1].Substring(tempArray[1].IndexOf("nyear=") + 6);
                string month  = tempArray[2].Substring(tempArray[2].IndexOf("nmonth=") + 7);
                string day    = tempArray[3].Substring(tempArray[3].IndexOf("nday=") + 5);
                string hour   = tempArray[5].Substring(tempArray[5].IndexOf("nhrs=") + 5);
                string minite = tempArray[6].Substring(tempArray[6].IndexOf("nmin=") + 5);
                string second = tempArray[7].Substring(tempArray[7].IndexOf("nsec=") + 5);
                dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second);
            }
            catch (WebException)
            {
                dt = DateTime.Now;
            }
            catch (Exception)
            {
                dt = DateTime.Now;
            }
            finally
            {
                if (wrp != null)
                {
                    wrp.Close();
                }
                if (wrt != null)
                {
                    wrt.Abort();
                }
            }
            return(dt);
        }
Exemplo n.º 26
0
        private object GetWebResponse(byte[] parameters)
#endif
        {
            WebRequest request = WebRequest.Create(URL);

            try
            {
                request.Credentials = CredentialCache.DefaultCredentials;

#if !NetFX_CORE
                request.Timeout = 10000;
                ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;

                if (headers != null)
                {
                    request.Headers.Add(headers);
                }
#endif

                if (contentType == ContentType.Form)
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }
                else if (contentType == ContentType.JSON)
                {
                    request.ContentType = "application/json";
                }

                if (requestType == RequestType.Get)
                {
                    request.Method = "GET";
                }
                else if (requestType == RequestType.Post)
                {
                    request.Method = "POST";
                }
                else if (requestType == RequestType.Put)
                {
                    request.Method = "PUT";
                }
                else if (requestType == RequestType.Delete)
                {
                    request.Method = "DELETE";
                }

                if (parameters != null)
                {
#if NetFX_CORE
                    Stream inputStream = await request.GetRequestStreamAsync();

                    inputStream.Write(parameters, 0, parameters.Length);
#else
                    using (Stream inputStream = request.GetRequestStream())
                    {
                        inputStream.Write(parameters, 0, parameters.Length);
                        inputStream.Close();
                        inputStream.Dispose();
                    }
#endif
                }

                string responseFromServer = string.Empty;
#if NetFX_CORE
                HttpWebResponse webResponse = (HttpWebResponse)request.GetResponseAsync().Result;
#else
                try
                {
                    using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
                    {
#endif
                using (Stream dataStream = webResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        responseFromServer = reader.ReadToEnd();
#if !NetFX_CORE
                        reader.Close();
#endif
                        reader.Dispose();
                    }

#if !NetFX_CORE
                    dataStream.Close();
#endif
                    dataStream.Dispose();
                }

#if NetFX_CORE
                webResponse.Dispose();
#else
                webResponse.Close();
            }
        }

        catch (Exception e)
        {
            request.Abort();
#if NetFX_CORE
            callback(e)
#else
            //TODO: If you need to see the error message, please debug it here.
            e = null;
            return(e);                            // JM: don't output the error to screen
#endif
        }
#endif

                request.Abort();
#if NetFX_CORE
                callback(responseFromServer);
#else
                return(responseFromServer);
#endif
            }
            catch (Exception e)
            {
                request.Abort();
#if NetFX_CORE
                callback(e);
#else
                return(e);
#endif
            }
        }
Exemplo n.º 27
0
        protected PureImage GetTileImageUsingHttp(string url)
        {
            PureImage ret = null;

#if !PocketPC
            WebRequest request = IsSocksProxy ? SocksHttpWebRequest.Create(url) : WebRequest.Create(url);
#else
            WebRequest request = WebRequest.Create(url);
#endif
            if (WebProxy != null)
            {
                request.Proxy = WebProxy;
            }

            if (Credential != null)
            {
                request.PreAuthenticate = true;
                request.Credentials     = Credential;
            }

            if (request is HttpWebRequest)
            {
                var r = request as HttpWebRequest;
                r.UserAgent        = UserAgent;
                r.ReadWriteTimeout = TimeoutMs * 6;
                r.Accept           = requestAccept;
                r.Referer          = RefererUrl;
                r.Timeout          = TimeoutMs;
            }
#if !PocketPC
            else if (request is SocksHttpWebRequest)
            {
                var r = request as SocksHttpWebRequest;

                if (!string.IsNullOrEmpty(UserAgent))
                {
                    r.Headers.Add("User-Agent", UserAgent);
                }

                if (!string.IsNullOrEmpty(requestAccept))
                {
                    r.Headers.Add("Accept", requestAccept);
                }

                if (!string.IsNullOrEmpty(RefererUrl))
                {
                    r.Headers.Add("Referer", RefererUrl);
                }
            }
#endif
            using (var response = request.GetResponse())
            {
                if (CheckTileImageHttpResponse(response))
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        MemoryStream data = Stuff.CopyStream(responseStream, false);

                        Debug.WriteLine("Response[" + data.Length + " bytes]: " + url);

                        if (data.Length > 0)
                        {
                            ret = TileImageProxy.FromStream(data);

                            if (ret != null)
                            {
                                ret.Data          = data;
                                ret.Data.Position = 0;
                            }
                            else
                            {
                                data.Dispose();
                            }
                        }
                        data = null;
                    }
                }
                else
                {
                    Debug.WriteLine("CheckTileImageHttpResponse[false]: " + url);
                }
#if PocketPC
                request.Abort();
#endif
                response.Close();
            }
            return(ret);
        }
Exemplo n.º 28
0
        ///<summary>
        /// 获取标准北京时间1
        ///</summary>
        ///<returns></returns>
        public static DateTime GetBJStandardTime()
        {
            //<?xml version="1.0" encoding="GB2312" ?>
            //- <ntsc>
            //- <time>
            //  <year>2011</year>
            //  <month>7</month>
            //  <day>10</day>
            //  <Weekday />
            //  <hour>19</hour>
            //  <minite>45</minite>
            //  <second>37</second>
            //  <Millisecond />
            //  </time>
            //  </ntsc>
            DateTime    dt;
            WebRequest  wrt = null;
            WebResponse wrp = null;

            try
            {
                wrt             = WebRequest.Create("http://www.time.ac.cn/timeflash.asp?user=flash");
                wrt.Credentials = CredentialCache.DefaultCredentials;
                ProxySetting(wrt);

                wrp = wrt.GetResponse();
                StreamReader sr   = new StreamReader(wrp.GetResponseStream(), Encoding.UTF8);
                string       html = sr.ReadToEnd();

                sr.Close();
                wrp.Close();

                int yearIndex   = html.IndexOf("<year>") + 6;
                int monthIndex  = html.IndexOf("<month>") + 7;
                int dayIndex    = html.IndexOf("<day>") + 5;
                int hourIndex   = html.IndexOf("<hour>") + 6;
                int miniteIndex = html.IndexOf("<minite>") + 8;
                int secondIndex = html.IndexOf("<second>") + 8;

                string year   = html.Substring(yearIndex, html.IndexOf("</year>") - yearIndex);
                string month  = html.Substring(monthIndex, html.IndexOf("</month>") - monthIndex);;
                string day    = html.Substring(dayIndex, html.IndexOf("</day>") - dayIndex);
                string hour   = html.Substring(hourIndex, html.IndexOf("</hour>") - hourIndex);
                string minite = html.Substring(miniteIndex, html.IndexOf("</minite>") - miniteIndex);
                string second = html.Substring(secondIndex, html.IndexOf("</second>") - secondIndex);
                dt = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day), int.Parse(hour), int.Parse(minite), int.Parse(second));
            }
            catch (WebException)
            {
                return(DateTime.Parse("2011-1-1"));
            }
            catch (Exception)
            {
                return(DateTime.Parse("2011-1-1"));
            }
            finally
            {
                if (wrp != null)
                {
                    wrp.Close();
                }
                if (wrt != null)
                {
                    wrt.Abort();
                }
            }
            return(dt);
        }
        /// <summary>
        /// Sends the asynchronous.
        /// </summary>
        /// <typeparam name="TRequest">The type of the request.</typeparam>
        /// <typeparam name="TResponse">The type of the response.</typeparam>
        /// <param name="method">The method.</param>
        /// <param name="requestBody">The request body.</param>
        /// <param name="request">The request.</param>
        /// <param name="setHeadersCallback">The set headers callback.</param>
        /// <returns>The response object.</returns>
        /// <exception cref="System.ArgumentNullException">request</exception>
        private async Task <TResponse> SendAsync <TRequest, TResponse>(string method, TRequest requestBody, WebRequest request, Action <WebRequest> setHeadersCallback = null)
        {
            try
            {
                if (request == null)
                {
                    throw new ArgumentNullException("request");
                }

                request.Method = method;
                if (null == setHeadersCallback)
                {
                    if (string.IsNullOrWhiteSpace(request.ContentType))
                    {
                        this.SetCommonHeaders(request);
                    }
                }
                else
                {
                    setHeadersCallback(request);
                }

                if (requestBody is Stream)
                {
                    //request.ContentType = "application/octet-stream";
                    request.ContentType = $"image/jpeg";
                }

                var asyncState = new WebRequestAsyncState()
                {
                    RequestBytes = this.SerializeRequestBody(requestBody),
                    WebRequest   = (HttpWebRequest)request,
                };

                var continueRequestAsyncState = await Task.Factory.FromAsync <Stream>(
                    asyncState.WebRequest.BeginGetRequestStream,
                    asyncState.WebRequest.EndGetRequestStream,
                    asyncState,
                    TaskCreationOptions.None).ContinueWith <WebRequestAsyncState>(
                    task =>
                {
                    var requestAsyncState = (WebRequestAsyncState)task.AsyncState;
                    if (requestBody != null)
                    {
                        using (var requestStream = task.Result)
                        {
                            if (requestBody is Stream)
                            {
                                (requestBody as Stream).CopyTo(requestStream);
                            }
                            else
                            {
                                requestStream.Write(requestAsyncState.RequestBytes, 0, requestAsyncState.RequestBytes.Length);
                            }
                        }
                    }

                    return(requestAsyncState);
                }).ConfigureAwait(false);

                var continueWebRequest = continueRequestAsyncState.WebRequest;
                var getResponseAsync   = Task.Factory.FromAsync <WebResponse>(
                    continueWebRequest.BeginGetResponse,
                    continueWebRequest.EndGetResponse,
                    continueRequestAsyncState);

                await Task.WhenAny(getResponseAsync, Task.Delay(DefaultTimeout)).ConfigureAwait(false);

                //Abort request if timeout has expired
                if (!getResponseAsync.IsCompleted)
                {
                    request.Abort();
                }

                return(this.ProcessAsyncResponse <TResponse>(getResponseAsync.Result as HttpWebResponse));
            }
            catch (AggregateException ae)
            {
                ae.Handle(e =>
                {
                    this.HandleException(e);
                    return(true);
                });
                return(default(TResponse));
            }
            catch (Exception e)
            {
                this.HandleException(e);
                return(default(TResponse));
            }
        }
Exemplo n.º 30
0
        ///<summary>
        /// 获取标准北京时间2
        ///</summary>
        ///<returns></returns>
        public static DateTime GetBeijingTime()
        {
            //t0 = new Date().getTime();
            //nyear = 2011;
            //nmonth = 7;
            //nday = 5;
            //nwday = 2;
            //nhrs = 17;
            //nmin = 12;
            //nsec = 12;
            DateTime    dt;
            WebRequest  wrt = null;
            WebResponse wrp = null;

            try
            {
                wrt             = WebRequest.Create("http://www.beijing-time.org/time.asp");
                wrt.Credentials = CredentialCache.DefaultCredentials;
                ProxySetting(wrt);

                wrp = wrt.GetResponse();

                string html = string.Empty;
                using (Stream stream = wrp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        html = sr.ReadToEnd();
                    }
                }

                string[] tempArray = html.Split(';');
                for (int i = 0; i < tempArray.Length; i++)
                {
                    tempArray[i] = tempArray[i].Replace("\r\n", "");
                }

                string year   = tempArray[1].Substring(tempArray[1].IndexOf("nyear=") + 6);
                string month  = tempArray[2].Substring(tempArray[2].IndexOf("nmonth=") + 7);
                string day    = tempArray[3].Substring(tempArray[3].IndexOf("nday=") + 5);
                string hour   = tempArray[5].Substring(tempArray[5].IndexOf("nhrs=") + 5);
                string minite = tempArray[6].Substring(tempArray[6].IndexOf("nmin=") + 5);
                string second = tempArray[7].Substring(tempArray[7].IndexOf("nsec=") + 5);
                dt = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day), int.Parse(hour), int.Parse(minite), int.Parse(second));
            }
            catch (WebException)
            {
                return(DateTime.Parse("2011-1-1"));
            }
            catch (Exception)
            {
                return(DateTime.Parse("2011-1-1"));
            }
            finally
            {
                if (wrp != null)
                {
                    wrp.Close();
                }
                if (wrt != null)
                {
                    wrt.Abort();
                }
            }
            return(dt);
        }