Exemplo n.º 1
0
        /// <summary>
        /// 初始化获取post请求参数
        /// </summary>
        private static void InitHttpRequestParams()
        {
            m_RequestParams = new ConcurrentDictionary <string, object>();

            foreach (var param in HttpContext.Current.Request.Form)
            {
                string param_name = param.ToString();

                object val = HttpContext.Current.Request.Params[param_name];

                if (UrlParams != null)
                {
                    if (UrlParams.ContainsKey(param_name))  //如果地址传的参数是否与post的参数键名相同
                    {
                        string v = val.ToString();

                        Type t = val.GetType();

                        v = v.Replace(",", string.Empty);
                        v = v.Replace(m_UrlParams[param_name].ToString(), string.Empty); //将地址上的参数的值替换为空

                        val = v;                                                         //剩下post的该参数的值
                    }
                }

                m_RequestParams.TryAdd(param_name, val);
            }
        }
Exemplo n.º 2
0
        public HttpResponseMessage GetResponse()
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine(FullURL);
#endif

            #region Local Variables
            WebRequestPostContentType postContentType = PostContentType;
            String     strPostContent = PostContent;
            HttpClient httpClient     = new HttpClient();
            httpClient.BaseAddress = new Uri(BaseURL);
            HttpResponseMessage httpResponse = null;
            #endregion Local Variables

            #region Resolve Headers
            foreach (KeyValuePair <String, String> kvp in Headers)
            {
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation(kvp.Key, kvp.Value);
            }
            #endregion Resolve Headers

            #region Resolve URL Path
            String strParam = URLParamsString;
            RequestPath = RequestPath.Replace('\\', '/');
            String urlPath = string.Format("{0}{1}{2}{3}", RequestPath, RequestPath.EndsWith("/") || strParam == "" ? "" : "/", strParam != "" ? "?" : "", strParam);
            #endregion Resolve URL Path

            switch (RequestType)
            {
            case WebRequestType.GET_OFFSET:
            case WebRequestType.GET_PAGE:
            case WebRequestType.POST_OFFSET:
            case WebRequestType.POST_PAGE:
                Int32   limit = 100, offset = 0, page = 0, maxPages = 20, maxChildren = 0;
                JObject jObjectMerged = new JObject(), jObjectTemp;
                Dictionary <string, string> dictPostContent = null;    //Used for POST_OFFSET and POST_PAGE

                #region Initialization by Request Type
                switch (RequestType)
                {
                case WebRequestType.GET_OFFSET:
                    if (UrlParams.ContainsKey(LimitField))
                    {
                        Int32.TryParse(UrlParams[LimitField], out limit);
                    }
                    else
                    {
                        UrlParams.Add(LimitField, limit.ToString());
                    }

                    if (UrlParams.ContainsKey(OffsetField))
                    {
                        Int32.TryParse(UrlParams[OffsetField], out offset);
                    }
                    else
                    {
                        UrlParams.Add(OffsetField, offset.ToString());
                    }
                    break;

                case WebRequestType.GET_PAGE:
                    if (UrlParams.ContainsKey(LimitField))
                    {
                        Int32.TryParse(UrlParams[LimitField], out limit);
                    }
                    else
                    {
                        UrlParams.Add(LimitField, limit.ToString());
                    }

                    if (UrlParams.ContainsKey(PageField))
                    {
                        Int32.TryParse(UrlParams[PageField], out page);
                    }
                    else
                    {
                        UrlParams.Add(PageField, page.ToString());
                    }
                    break;

                case WebRequestType.POST_OFFSET:
                    dictPostContent = new Dictionary <string, string>
                    {
                        { LimitField, Limit.ToString() },
                        { OffsetField, offset.ToString() }
                    };
                    break;

                case WebRequestType.POST_PAGE:
                    dictPostContent = new Dictionary <string, string>
                    {
                        { LimitField, Limit.ToString() },
                        { PageField, page.ToString() }
                    };
                    break;
                }
                #endregion Initialization by Request Type

                do
                {
                    #region Loop Initialization
                    switch (RequestType)
                    {
                    case WebRequestType.GET_OFFSET:
                        UrlParams[OffsetField] = offset.ToString();
                        break;

                    case WebRequestType.GET_PAGE:
                        UrlParams[PageField] = page.ToString();
                        break;

                    case WebRequestType.POST_OFFSET:
                        dictPostContent[OffsetField] = offset.ToString();
                        break;

                    case WebRequestType.POST_PAGE:
                        dictPostContent[PageField] = page.ToString();
                        break;
                    }
                    #endregion Loop Initialization

                    strParam = URLParamsString;
                    urlPath  = string.Format("{0}{1}{2}{3}", RequestPath, RequestPath.EndsWith("/") ? "" : "/", strParam != "" ? "?" : "", strParam);

                    #region Get the Response by Request Type
                    switch (RequestType)
                    {
                    case WebRequestType.GET_OFFSET:
                    case WebRequestType.GET_PAGE:
                        httpResponse = httpClient.GetAsync(urlPath).Result;
                        break;

                    case WebRequestType.POST_OFFSET:
                    case WebRequestType.POST_PAGE:
                        FormUrlEncodedContent postContent = new FormUrlEncodedContent(dictPostContent);
                        httpResponse = httpClient.PostAsync(urlPath, postContent).Result;
                        break;
                    }
                    #endregion Get the Response by Request Type

                    #region Break out if StatusCode is not OK
                    if (httpResponse.StatusCode != HttpStatusCode.OK)
                    {
                        break;
                    }
                    #endregion Break out if StatusCode is not OK

                    String strResponse = httpResponse.Content.ReadAsStringAsync().Result;
                    if (strResponse.StartsWith("[") && strResponse.EndsWith("]"))
                    {
                        strResponse = $"{{\"root\":{strResponse}}}";
                    }
                    jObjectTemp = JObject.Parse(strResponse);
                    IEnumerable <JToken> allTokens = jObjectTemp.SelectTokens("*");
                    maxChildren = allTokens.Select(t => t.Count()).Max();
                    jObjectMerged.Merge(jObjectTemp);
                    page++;
                    offset += limit;
                } while (maxChildren > 1 && maxChildren >= limit && page <= maxPages);

                httpResponse.Content = new StringContent(jObjectMerged.ToString(), Encoding.UTF8, "application/json");
                break;

            case WebRequestType.CANCEL:
                httpClient.CancelPendingRequests();
                break;

            case WebRequestType.DELETE:
                httpResponse = httpClient.DeleteAsync(urlPath).Result;
                break;

            case WebRequestType.GET:
            default:
                httpResponse = httpClient.GetAsync(urlPath).Result;
                break;

            case WebRequestType.POST:
            case WebRequestType.PUT:
            case WebRequestType.SEND:
                #region Resolve MediaType
                String mediaType;

                switch (postContentType)
                {
                case WebRequestPostContentType.STRING:
                case WebRequestPostContentType.FORM_URL_ENCODED:
                default:
                    mediaType = "text/plain";
                    break;

                case WebRequestPostContentType.JSON:
                    mediaType = "application/json";
                    break;

                case WebRequestPostContentType.XML:
                case WebRequestPostContentType.SOAP:
                case WebRequestPostContentType.SOAP_STRING:
                    mediaType = "text/xml";
                    break;
                }
                #endregion Resolve MediaType

                #region Resolve Content
                HttpContent content;

                switch (postContentType)
                {
                case WebRequestPostContentType.XML:
                case WebRequestPostContentType.JSON:
                case WebRequestPostContentType.STRING:
                default:
                    content = new StringContent(strPostContent, Encoding.UTF8, mediaType);
                    break;

                case WebRequestPostContentType.FORM_URL_ENCODED:
                    Dictionary <String, String> formData = strPostContent.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(part => part.Split('='))
                                                           .ToDictionary(split => split[0], split => split[1]);
                    content = new FormUrlEncodedContent(formData);
                    break;

                case WebRequestPostContentType.SOAP:
                case WebRequestPostContentType.SOAP_STRING:
                    content = new StringContent(String.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
                        <s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
                            <s:Body>
                                {0}
                            </s:Body>
                        </s:Envelope>", strPostContent), Encoding.UTF8, mediaType);
                    break;
                }
                #endregion Resolve Content

                switch (RequestType)
                {
                case WebRequestType.POST:
                    httpResponse = httpClient.PostAsync(urlPath, content).Result;
                    break;

                case WebRequestType.PUT:
                    httpResponse = httpClient.PutAsync(urlPath, content).Result;
                    break;

                case WebRequestType.SEND:
                    HttpRequestMessage httpContent = new HttpRequestMessage(HttpMethod.Post, urlPath)
                    {
                        Content = content, Version = HttpVersion.Version11
                    };
                    httpResponse = httpClient.SendAsync(httpContent).Result;
                    break;
                }
                break;
            }

            return(httpResponse);
        }