Example #1
0
        /// <summary>
        /// Compress a string
        /// </summary>
        public static string WebCompress(string Body, EnumContentType ContentType)
        {
            Log.Clear();
            Log.Write("Starting Compression");
            Log.Write("Content type: " + ContentType.ToString());


            if (ContentType == EnumContentType.Javascript)
            {
                #region Remove Javascript Comments (2014 new method... may be buggy)
                //var blockComments = @"/\*(.*?)\*/";
                //var lineComments = @"//(.*?)\r?\n";
                //var strings = @"""((\\[^\n]|[^""\n])*)""";
                //var verbatimStrings = @"@(""[^""]*"")+";

                /*
                 * string strBodyNoComments = Regex.Replace(Body,
                 * blockComments + "|" + lineComments + "|" + strings + "|" + verbatimStrings,
                 * me =>
                 * {
                 *  if (me.Value.StartsWith("/*") || me.Value.StartsWith("//"))
                 *      return me.Value.StartsWith("//") ? "\r\n" : "";
                 *  // Keep the literal strings
                 *  return me.Value;
                 * },
                 * RegexOptions.Singleline);
                 *
                 * Body = strBodyNoComments;
                 */
                #endregion
            }

            string[] lines;
            string   line;
            int      char_pos = 0;
            string   buffer   = "";
            lines = Body.Split('\n');
            EnumLineClass line_class;
            if (ContentType == EnumContentType.Javascript)
            {
                line_class = EnumLineClass.Javascript;
            }
            else
            {
                line_class = EnumLineClass.HTML;
            }

            for (int i = 0; i < lines.Length; i++)
            {
                line       = lines[i];
                line_class = GetLineClass(line, line_class);
                buffer    += WebCompressLine(line, line_class, i + 1, char_pos); //+ "\n"
                char_pos  += line.Length;
            }
            Log.Write("Compression Complete");
            return(buffer);
        }
Example #2
0
        public string RequestPost(string requestQuery, string requestBody, EnumContentType contentType)
        {
            HttpWebRequest request = GetRequest("POST", $"{_url}/{requestQuery}", contentType);

            using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(requestBody);
            }

            return(GetResponse(request));
        }
Example #3
0
        private static HttpWebRequest GetRequest(string method, string url, EnumContentType contentType)
        {
            var request = WebRequest.CreateHttp(new Uri(url));

            request.ContentType            = ConvertContentTypeToString(contentType);
            request.AutomaticDecompression = DecompressionMethods.GZip;
            request.Proxy.Credentials      = CredentialCache.DefaultNetworkCredentials;
            request.Method    = method;
            request.UserAgent = UserAgentService.GetUserAgent();
            request.Timeout   = 60000;

            return(request);
        }
Example #4
0
        /// <summary>
        /// Compress a string
        /// </summary>
        public static string WebCompress(string Body, EnumContentType ContentType)
        {
            Log.Clear();
            Log.Write("Starting Compression");
            Log.Write("Content type: " + ContentType.ToString());

            if (ContentType == EnumContentType.Javascript)
            {
                #region Remove Javascript Comments (2014 new method... may be buggy)
                //var blockComments = @"/\*(.*?)\*/";
                //var lineComments = @"//(.*?)\r?\n";
                //var strings = @"""((\\[^\n]|[^""\n])*)""";
                //var verbatimStrings = @"@(""[^""]*"")+";
                /*
                string strBodyNoComments = Regex.Replace(Body,
                blockComments + "|" + lineComments + "|" + strings + "|" + verbatimStrings,
                me =>
                {
                    if (me.Value.StartsWith("/*") || me.Value.StartsWith("//"))
                        return me.Value.StartsWith("//") ? "\r\n" : "";
                    // Keep the literal strings
                    return me.Value;
                },
                RegexOptions.Singleline);

                Body = strBodyNoComments;
                */
                #endregion
            }

            string[] lines;
            string line;
            int char_pos = 0;
            string buffer = "";
            lines = Body.Split('\n');
            EnumLineClass line_class;
            if(ContentType == EnumContentType.Javascript)
                line_class = EnumLineClass.Javascript;
            else
                line_class = EnumLineClass.HTML;

            for(int i = 0; i<lines.Length; i++)
            {
                line = lines[i];
                line_class = GetLineClass(line, line_class);
                buffer += WebCompressLine(line, line_class, i + 1, char_pos); //+ "\n"
                char_pos+= line.Length;
            }
            Log.Write("Compression Complete");
            return(buffer);
        }
Example #5
0
        private static string ConvertContentTypeToString(EnumContentType type)
        {
            switch (type)
            {
            case EnumContentType.Html:
                return("application/x-www-form-urlencoded; charset=UTF-8");

            case EnumContentType.Json:
                return("application/json");

            case EnumContentType.Post:
                return("application/x-www-form-urlencoded");

            default:
                return("application/x-www-form-urlencoded");
            }
        }
Example #6
0
        private static string GetAPIContentType(EnumContentType ContentType)
        {
            string result = "";

            switch (ContentType)
            {
            case EnumContentType.json:
                result = "application/json";
                break;

            case EnumContentType.formurlencoded:
                result = "application/x-www-form-urlencoded";
                break;

            default:
                throw new Exception("Unknown ContentType.");
            }

            return(result);
        }
Example #7
0
        private static string GetAPIContentType(EnumContentType ContentType)
        {
            string result;

            switch (ContentType)
            {
            case EnumContentType.json:
                result = ConstSetting.ContentTypeJson;
                break;

            case EnumContentType.formurlencoded:
                result = ConstSetting.ContentTypeform;
                break;

            default:
                throw new Exception("Unknown ContentType.");
            }

            return(result);
        }
Example #8
0
 public static T PostApi <T>(EnumApiServer apiServer, EnumContentType contentType, EnumApiMethodType apiMethodType, string controllerName, string actionName, string getParam, object parameter, bool isJson = true)
 {
     return(Api <T>(apiServer, contentType, EnumApiMethodType.Post, controllerName + "/" + actionName, getParam, parameter, isJson));
 }
Example #9
0
        public static T Api <T>(EnumApiServer apiServer, EnumContentType contentType, EnumApiMethodType apiMethodType, string methodName, string getParam, object parameter, bool isJson = true)
        {
            if (!string.IsNullOrWhiteSpace(getParam) && !getParam.StartsWith("/"))
            {
                getParam = "/" + getParam.Trim();
            }
            else if (string.IsNullOrWhiteSpace(getParam))
            {
                getParam = "";
            }

            // 整理呼叫的url
            string apiURL = CombinePath(GetAPIServerBasePath(apiServer), methodName) + getParam;

            HttpWebRequest request     = HttpWebRequest.Create(apiURL) as HttpWebRequest;
            string         PostTypeStr = "";

            switch (apiMethodType)
            {
            case EnumApiMethodType.Post:
                PostTypeStr = WebRequestMethods.Http.Post;
                break;

            case EnumApiMethodType.Get:
                PostTypeStr = WebRequestMethods.Http.Get;
                break;

            case EnumApiMethodType.Put:
                PostTypeStr = WebRequestMethods.Http.Put;
                break;

            default:
                break;
            }
            request.Method      = PostTypeStr;                                                    // 方法
            request.KeepAlive   = true;                                                           //是否保持連線
            request.ContentType = GetAPIContentType(contentType);
            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; //for https
            // 讓這個request最多等10分鐘
            request.Timeout = 600000;
            request.MaximumResponseHeadersLength = int.MaxValue;
            request.MaximumAutomaticRedirections = int.MaxValue;
            request.AutomaticDecompression       = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            try
            {
                // 整理成呼叫的body paramter
                if (apiMethodType != EnumApiMethodType.Get)
                {
                    string JSONParameterString = SerializeToJson <object>(parameter);
                    byte[] bs = System.Text.Encoding.UTF8.GetBytes(JSONParameterString);
                    using (Stream reqStream = request.GetRequestStream())
                    {
                        reqStream.Write(bs, 0, bs.Length);
                    }
                }
                string jsonResult = "";
                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var temp = reader.ReadToEnd();
                            jsonResult = temp;
                            //TODO:反序列化
                            if (temp == "" || temp == "null")
                            {
                                return(default(T));
                            }
                            else
                            {
                                T result = default(T);
                                if (isJson)
                                {
                                    result = DeserializeJson <T>(jsonResult);
                                }
                                else
                                {
                                    result = (T)Convert.ChangeType(temp, typeof(T));
                                }
                                return(result);
                            }
                        }
                    }
                }
            }
            catch (WebException webException)
            {
                if (webException.Response == null)
                {
                    throw new Exception("服務無回應", webException);
                }
                using (StreamReader reader = new StreamReader(webException.Response.GetResponseStream()))
                {
                    HttpWebResponse res         = (HttpWebResponse)webException.Response;
                    var             pageContent = reader.ReadToEnd();
                    T result = JsonConvert.DeserializeObject <T>(pageContent);
                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #10
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);
        }
Example #11
0
        /// <summary>
        /// Compress a string and send to HtmlTextWriter
        /// </summary>
        public static void WebCompress(string Body, System.Web.UI.HtmlTextWriter Writer, EnumContentType ContentType)
        {
            Log.Clear();
            Log.Write("Starting Compression");
            Log.Write("Content type: " + ContentType.ToString());

            string[] lines;
            string line;
            int char_pos = 0;
            lines = Body.Split('\n');
            EnumLineClass line_class;
            if(ContentType == EnumContentType.Javascript)
                line_class = EnumLineClass.Javascript;
            else
                line_class = EnumLineClass.HTML;

            for(int i = 0; i<lines.Length; i++)
            {
                line = lines[i];
                line_class = GetLineClass(line,line_class);
                Writer.Write(WebCompressLine(line,line_class,i + 1,char_pos));
                char_pos+= line.Length;
            }
            Log.Write("Compression Complete");
        }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T">返回转换的类型</typeparam>
        /// <param name="strUri">地址</param>
        /// <param name="method">请求方式</param>
        /// <param name="contentType">请求接收类型</param>
        /// <param name="objToSend">发送的数据(只限于Post和Put)</param>
        /// <param name="tick">防止等幂提交(只限于Put和Delete)</param>
        /// <returns></returns>
        public static ResponseResult <T> DoRequest <T>(string strUri, EnumHttpMethod method,
                                                       EnumContentType contentType = EnumContentType.Json,
                                                       Object objToSend            = null, long tick = 0)
        {
            string strToRequest = strUri;

            if (tick != 0 && (method == EnumHttpMethod.PUT || method == EnumHttpMethod.DELETE))
            {
                strToRequest += "?UpdateTicks=" + tick.ToString(CultureInfo.InvariantCulture);//CultureInfo.InvariantCulture的作用是为了固定格式
            }
            //表示一个HTTP请求消息。
            HttpRequestMessage requestMsg = new HttpRequestMessage();

            //设置HTTP接收请求的数据类型
            switch (contentType)
            {
            case EnumContentType.Json:
                requestMsg.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(HttpContentTypes.ApplicationJson));
                break;

            case EnumContentType.Xml:
                requestMsg.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(HttpContentTypes.ApplicationXml));
                break;
            }
            //请求数据的链接(Uri)
            requestMsg.RequestUri = new Uri(strToRequest);

            HttpContent content = null;

            if (objToSend != null)
            {
                //StringContent():转换成基于字符串的HTTP内容。
                //JsonConvert.SerializeObject(objToSend):将实体对象序列化成JSON
                switch (contentType)
                {
                case EnumContentType.Json:
                    content = new StringContent(JsonConvert.SerializeObject(objToSend), Encoding.UTF8, "application/json");
                    break;

                case EnumContentType.Xml:
                    content = new StringContent(SerializeUtil.SerializeToXml(objToSend), Encoding.UTF8, "application/xml");
                    break;

                case EnumContentType.String:
                    content = new StringContent(objToSend.ToString());
                    break;
                }
            }


            switch (method)
            {
            case EnumHttpMethod.POST:
                requestMsg.Method  = HttpMethod.Post;   //Post用于新增
                requestMsg.Content = content;
                break;

            case EnumHttpMethod.PUT:
                requestMsg.Method  = HttpMethod.Put;   //Put用于修改
                requestMsg.Content = content;
                break;

            case EnumHttpMethod.DELETE:
                requestMsg.Method = HttpMethod.Delete;
                break;

            default:
                requestMsg.Method = HttpMethod.Get;    //Get用于获取
                break;
            }
            //client是HttpClient的对象:用于发送HTTP请求和接收HTTP响应
            HttpClient client = new HttpClient();
            //client.SendAsync:发送一个HTTP请求一个异步操作,并返回响应结果。
            Task <HttpResponseMessage> rtnAll = client.SendAsync(requestMsg);

            #region 执行
            HttpResponseMessage resultMessage = null;
            Task <T>            rtnFinal;

            try
            {
                //这一步是关键提交请求的过程,rtnAll.Result这里其实是一个多线程的处理,是.Net Framework 4.0的新特性之一
                resultMessage = rtnAll.Result;
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.InnerExceptions)
                {
                    if (ex is HttpRequestException)
                    {
                        throw new Exception("发送网络请求失败", ex);
                    }
                }
            }
            finally
            {
                client.Dispose();
            }

            if (!resultMessage.IsSuccessStatusCode)//判断响应是否成功?
            {
                resultMessage.EnsureSuccessStatusCode();
            }

            try
            {
                switch (contentType)
                {
                case EnumContentType.Xml:
                    rtnFinal = resultMessage.Content.ReadAsAsync <T>(new MediaTypeFormatter[] { new XmlMediaTypeFormatter() });
                    break;

                default:
                    rtnFinal = resultMessage.Content.ReadAsAsync <T>(new MediaTypeFormatter[] { new JsonMediaTypeFormatter() });
                    break;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("服务器返回与请求不匹配", ex);
            }

            #endregion

            return(new ResponseResult <T>()
            {
                Value = rtnFinal.Result,
                RawValue = resultMessage.Content.ReadAsStringAsync().Result
            });
        }
Example #13
0
        public string RequestGet(string requestQuery, EnumContentType contentType)
        {
            HttpWebRequest request = GetRequest("GET", $"{_url}/{requestQuery}", contentType);

            return(GetResponse(request));
        }
Example #14
0
        /// <summary>
        /// Compress a string and send to HtmlTextWriter
        /// </summary>
        public static void WebCompress(string Body, System.Web.UI.HtmlTextWriter Writer, EnumContentType ContentType)
        {
            Log.Clear();
            Log.Write("Starting Compression");
            Log.Write("Content type: " + ContentType.ToString());

            string[] lines;
            string   line;
            int      char_pos = 0;

            lines = Body.Split('\n');
            EnumLineClass line_class;

            if (ContentType == EnumContentType.Javascript)
            {
                line_class = EnumLineClass.Javascript;
            }
            else
            {
                line_class = EnumLineClass.HTML;
            }

            for (int i = 0; i < lines.Length; i++)
            {
                line       = lines[i];
                line_class = GetLineClass(line, line_class);
                Writer.Write(WebCompressLine(line, line_class, i + 1, char_pos));
                char_pos += line.Length;
            }
            Log.Write("Compression Complete");
        }