Exemplo n.º 1
0
        public virtual Guid RequestStringAsync(EnumRequestMethod requestMethod)
        {
            Guid taskId = Guid.NewGuid();

            RequestStringAsync(requestMethod, taskId);
            return(taskId);
        }
Exemplo n.º 2
0
        private HttpWebRequest GetRequestObj(EnumRequestMethod requestMethod)
        {
            HttpWebRequest objHWR = (HttpWebRequest)HttpWebRequest.Create(Url);

            objHWR.Timeout   = Timeout;
            objHWR.UserAgent = UserAgent;
            objHWR.Accept    = "*/*";// Accept;
            objHWR.Referer   = Referer;
            objHWR.KeepAlive = true;

            if (X_FORWARDED_FOR != string.Empty)
            {
                objHWR.Headers.Set("X_FORWARDED_FOR", X_FORWARDED_FOR);
            }
            if (Proxy != null)
            {
                objHWR.Proxy = Proxy;
            }
            if (Cookie != null)
            {
                objHWR.CookieContainer = Cookie;
            }

            if (requestMethod == EnumRequestMethod.GET)
            {
                objHWR.Method = "GET";
            }
            else
            {
                objHWR.Method      = "POST";
                objHWR.ContentType = this.ContentType;

                //Stream newStream = null;
                //try
                //{
                //    byte[] byteData = Encoding.ASCII.GetBytes(PostData);
                //    objHWR.ContentLength = byteData.Length;
                //    newStream = objHWR.GetRequestStream();
                //    // Send the data.
                //    newStream.Write(byteData, 0, byteData.Length);
                //    newStream.Close();
                //}
                //catch (WebException ex)
                //{
                //    if (newStream != null)
                //    {
                //        newStream.Close();
                //    }
                //    if (objHWR != null)
                //    {
                //        objHWR.Abort();
                //    }
                //    throw ex;
                //}
            }
            return(objHWR);
        }
Exemplo n.º 3
0
        // 这个方法开始真正的请求过程
        // 运行在单独的线程中
        private void RequestStringWorker(
            EnumRequestMethod requestMethod,
            AsyncOperation asyncOp)
        {
            Stream    responseStream;
            string    responseString = string.Empty;
            Exception e = null;

            // Check that the task is still active.
            // The operation may have been canceled before
            // the thread was scheduled.
            if (!TaskCanceled(asyncOp.UserSuppliedState))
            {
                try
                {
                    switch (requestMethod)
                    {
                    case EnumRequestMethod.GET:
                        responseStream = this.HttpGetStream();
                        break;

                    case EnumRequestMethod.POST:
                        responseStream = this.HttpPostStream();
                        break;

                    default:     //默认是POST
                        responseStream = this.HttpPostStream();
                        break;
                    }
                    if (responseStream != null)
                    {
                        responseString = GetResponseString(responseStream);
                    }
                    else
                    {
                        throw new Exception("返回的网络流为空!");
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    e = ex;
                }
            }

            this.CompletionMethod(
                responseString,
                e,
                TaskCanceled(asyncOp.UserSuppliedState),
                asyncOp);

            //completionMethodDelegate(calcState);
        }
Exemplo n.º 4
0
        // 这个方法开始真正的请求过程
        // 运行在单独的线程中
        private void RequestDataWorker(
            EnumRequestMethod requestMethod,
            AsyncOperation asyncOp)
        {
            byte[]          responseData = null;
            HttpWebResponse response     = null;
            Exception       e            = null;

            if (!TaskCanceled(asyncOp.UserSuppliedState))
            {
                try
                {
                    switch (requestMethod)
                    {
                    case EnumRequestMethod.GET:
                        response = this.HttpGetMethod();
                        break;

                    case EnumRequestMethod.POST:
                        response = this.HttpPostMethod();
                        break;

                    default:     //默认是POST
                        response = this.HttpPostMethod();
                        break;
                    }
                    if (response != null)
                    {
                        responseData = GetResponseData(response);
                    }
                    else
                    {
                        throw new Exception("返回的Response对象为空!");
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    e = ex;
                }
            }

            this.CompletionMethod(
                responseData,
                e,
                TaskCanceled(asyncOp.UserSuppliedState),
                asyncOp);

            //completionMethodDelegate(calcState);
        }
Exemplo n.º 5
0
        // This method starts an asynchronous calculation.
        // First, it checks the supplied task ID for uniqueness.
        // If taskId is unique, it creates a new WorkerEventHandler
        // and calls its BeginInvoke method to start the calculation.
        public virtual void RequestDataAsync(
            EnumRequestMethod requestMethod,
            object taskId)
        {
            //HttpWebRequest requestObj = GetRequestObj(requestMethod);
            //RequestState requestState = new RequestState();
            //requestState.request = requestObj;
            //requestState.RequestId = taskId;
            //requestState.IsRequestString = false;
            //requestState.Context = SynchronizationContext.Current;
            //if (requestMethod == EnumRequestMethod.POST)
            //{
            //    requestState.PostData = this.PostData;
            //}
            //requestState.RequestMethod = requestMethod;
            //this.BeginHttpReqeust(requestState);

            // Create an AsyncOperation for taskId.

            AsyncOperation asyncOp =
                AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                              "Task ID parameter must be unique",
                              "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }

            // Start the asynchronous operation.
            WorkerEventHandler workerDelegate = new WorkerEventHandler(RequestDataWorker);

            workerDelegate.BeginInvoke(
                requestMethod,
                asyncOp,
                null,
                null);
        }
Exemplo n.º 6
0
        /// <summary>
        /// http请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="requestData">请求数据</param>
        /// <param name="contentType">设置 Content-type HTTP 标头的值</param>
        /// <param name="method">请求方式</param>
        /// <param name="timeout">超时时间</param>
        /// <param name="charset"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        public static string HttpRequest(string url, string requestData, EnumContentType contentType = EnumContentType.Form, EnumRequestMethod method = EnumRequestMethod.Get, int timeout = 30, string charset = "utf-8")
        {
            string     rawUrl = string.Empty;
            UriBuilder uri    = new UriBuilder(url);
            string     result = string.Empty;

            switch (method)
            {
            case EnumRequestMethod.Get:
            {
                if (!string.IsNullOrEmpty(requestData))
                {
                    uri.Query = requestData;
                }
            }
            break;
            }
            HttpWebRequest http = WebRequest.Create(uri.Uri) as HttpWebRequest;

            http.ServicePoint.Expect100Continue = false;
            http.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
            http.Timeout   = timeout * 1000;
            // http.Referer = "";
            if (string.IsNullOrEmpty(charset))
            {
                charset = "utf-8";
            }
            Encoding encoding = Encoding.GetEncoding(charset);

            switch (method)
            {
            case EnumRequestMethod.Get:
            {
                http.Method = "GET";
            }
            break;

            case EnumRequestMethod.Post:
            {
                http.Method = "POST";
                switch (contentType)
                {
                case EnumContentType.Form:
                    http.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
                    break;

                case EnumContentType.Json:
                    http.ContentType = "application/json";
                    break;

                case EnumContentType.Xml:
                    http.ContentType = "text/xml";
                    break;

                default:
                    http.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
                    break;
                }

                byte[] bytesRequestData = encoding.GetBytes(requestData);
                http.ContentLength = bytesRequestData.Length;
                using (Stream requestStream = http.GetRequestStream())
                {
                    requestStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                }
            }
            break;
            }
            using (WebResponse webResponse = http.GetResponse())
            {
                using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                    reader.Close();
                }
                webResponse.Close();
            }
            http = null;
            return(result);
        }
Exemplo n.º 7
0
        // 这个方法开始真正的请求过程
        // 运行在单独的线程中
        private void RequestDataWorker(
            EnumRequestMethod requestMethod,
            AsyncOperation asyncOp)
        {

            byte[] responseData = null;
            HttpWebResponse response = null;
            Exception e = null;
            if (!TaskCanceled(asyncOp.UserSuppliedState))
            {
                try
                {
                    switch (requestMethod)
                    {
                        case EnumRequestMethod.GET:
                            response = this.HttpGetMethod();
                            break;
                        case EnumRequestMethod.POST:
                            response = this.HttpPostMethod();
                            break;
                        default: //默认是POST
                            response = this.HttpPostMethod();
                            break;
                    }
                    if (response != null)
                    {
                        responseData = GetResponseData(response);
                    }
                    else
                    {
                        throw new Exception("返回的Response对象为空!");
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    e = ex;
                }
            }

            this.CompletionMethod(
                responseData,
                e,
                TaskCanceled(asyncOp.UserSuppliedState),
                asyncOp);

            //completionMethodDelegate(calcState);
        }
Exemplo n.º 8
0
        // 这个方法开始真正的请求过程
        // 运行在单独的线程中
        private void RequestStringWorker(
            EnumRequestMethod requestMethod,
            AsyncOperation asyncOp)
        {

            Stream responseStream;
            string responseString = string.Empty;
            Exception e = null;

            // Check that the task is still active.
            // The operation may have been canceled before
            // the thread was scheduled.
            if (!TaskCanceled(asyncOp.UserSuppliedState))
            {
                try
                {
                    switch (requestMethod)
                    {
                        case EnumRequestMethod.GET:
                            responseStream = this.HttpGetStream();
                            break;
                        case EnumRequestMethod.POST:
                            responseStream = this.HttpPostStream();
                            break;
                        default: //默认是POST
                            responseStream = this.HttpPostStream();
                            break;
                    }
                    if (responseStream != null)
                    {
                        responseString = GetResponseString(responseStream);
                    }
                    else
                    {
                        throw new Exception("返回的网络流为空!");
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    e = ex;
                }
            }

            this.CompletionMethod(
                responseString,
                e,
                TaskCanceled(asyncOp.UserSuppliedState),
                asyncOp);

            //completionMethodDelegate(calcState);
        }
Exemplo n.º 9
0
        private HttpWebRequest GetRequestObj(EnumRequestMethod requestMethod)
        {
            HttpWebRequest objHWR = (HttpWebRequest)HttpWebRequest.Create(Url);
            objHWR.Timeout = Timeout;
            objHWR.UserAgent = UserAgent;
            objHWR.Accept = "*/*";// Accept;
            objHWR.Referer = Referer;
            objHWR.KeepAlive = true;

            if (X_FORWARDED_FOR != string.Empty)
            {
                objHWR.Headers.Set("X_FORWARDED_FOR", X_FORWARDED_FOR);
            }
            if (Proxy != null)
            {
                objHWR.Proxy = Proxy;
            }
            if (Cookie != null)
            {
                objHWR.CookieContainer = Cookie;
            }

            if (requestMethod == EnumRequestMethod.GET)
            {
                objHWR.Method = "GET";
            }
            else
            {
                objHWR.Method = "POST";
                objHWR.ContentType = this.ContentType;

                //Stream newStream = null;
                //try
                //{
                //    byte[] byteData = Encoding.ASCII.GetBytes(PostData);
                //    objHWR.ContentLength = byteData.Length;
                //    newStream = objHWR.GetRequestStream();
                //    // Send the data.
                //    newStream.Write(byteData, 0, byteData.Length);
                //    newStream.Close();
                //}
                //catch (WebException ex)
                //{
                //    if (newStream != null)
                //    {
                //        newStream.Close();
                //    }
                //    if (objHWR != null)
                //    {
                //        objHWR.Abort();
                //    }
                //    throw ex;
                //}
            }
            return objHWR;
        }
Exemplo n.º 10
0
        public virtual void RequestStringAsync(
            EnumRequestMethod requestMethod,
            object taskId)
        {

            //HttpWebRequest requestObj = GetRequestObj(requestMethod);
            //RequestState requestState = new RequestState();
            //requestState.request = requestObj;
            //requestState.RequestId = taskId;
            //requestState.IsRequestString = true;
            //requestState.Context = SynchronizationContext.Current;
            //if (requestMethod == EnumRequestMethod.POST)
            //{
            //    requestState.PostData = this.PostData;
            //}
            //requestState.RequestMethod = requestMethod;
            //this.BeginHttpReqeust(requestState);
            // Create an AsyncOperation for taskId.

            AsyncOperation asyncOp =
                AsyncOperationManager.CreateOperation(taskId);

            // Multiple threads will access the task dictionary,
            // so it must be locked to serialize access.
            lock (userStateToLifetime.SyncRoot)
            {
                if (userStateToLifetime.Contains(taskId))
                {
                    throw new ArgumentException(
                        "Task ID parameter must be unique",
                        "taskId");
                }

                userStateToLifetime[taskId] = asyncOp;
            }

            // Start the asynchronous operation.
            WorkerEventHandler workerDelegate = new WorkerEventHandler(RequestStringWorker);
            workerDelegate.BeginInvoke(
                requestMethod,
                asyncOp,
                null,
                null);

        }
Exemplo n.º 11
0
 public virtual Guid RequestStringAsync(EnumRequestMethod requestMethod)
 {
     Guid taskId = Guid.NewGuid();
     RequestStringAsync(requestMethod, taskId);
     return taskId;
 }