Esempio n. 1
0
        /// <summary>
        /// 将正文格式化为字节流
        /// </summary>
        /// <param name="format"> 包含格式规范的格式字符串 </param>
        /// <param name="body"> 请求或响应正文 </param>
        /// <param name="formatProvider"> 它提供有关当前实例的格式信息 </param>
        /// <returns> </returns>
        public override byte[] Serialize(string format, IEnumerable <KeyValuePair <string, object> > body, IFormatProvider formatProvider)
        {
            if (_UrlEncodedBuilder == null)
            {
                _UrlEncodedBuilder = new HttpUrlEncodedBuilder();
            }
            else
            {
                _UrlEncodedBuilder.Clear(null);
            }
            var request = formatProvider.GetFormat(typeof(IHttpRequest)) as IHttpRequest;

            _UrlEncodedBuilder.ArrayEncodeMode  = request?.Query.ArrayEncodeMode ?? ArrayEncodeMode.Default;
            _UrlEncodedBuilder.ObjectEncodeMode = request?.Query.ObjectEncodeMode ?? ObjectEncodeMode.Default;
            foreach (var item in body)
            {
                _UrlEncodedBuilder.AppendObject(item.Key, item.Value);
            }
            var encoding = GetEncoding(formatProvider) ?? Encoding.ASCII;

            return(encoding.GetBytes(_UrlEncodedBuilder.ToString()));
        }
Esempio n. 2
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="request"> </param>
        public HttpRequestData(IHttpRequest request)
            : this()
        {
            var url = request.BaseUrl.Combine(request.Path);

            if (url == null)
            {
                throw new UriFormatException("url不能为空");
            }
            if (_UrlEncodedBuilder == null)
            {
                _UrlEncodedBuilder = new HttpUrlEncodedBuilder();
            }
            _UrlEncodedBuilder.ArrayEncodeMode  = request.Query.ArrayEncodeMode;
            _UrlEncodedBuilder.ObjectEncodeMode = request.Query.ObjectEncodeMode;

            if (request.Version != null)
            {
                Version = request.Version;
            }
            else if (url.Scheme == Uri.UriSchemeHttps)
            {
                Version = HttpVersion.Version10;
            }
            else
            {
                Version = HttpVersion.Version11;
            }

            Host          = new Uri(url, "/");
            Timeout       = Debugger.IsAttached ? TimeSpan.MaxValue : request.Timeout; //调试时不会因为断点时间太久而超时
            Request       = request;
            Method        = request.HttpMethod;
            Proxy         = request.Proxy;
            SchemeVersion = $"{url.Scheme.ToUpperInvariant()}/{Version}";

            _provider = request.Body.ContentType;
            // ReSharper disable once ImpureMethodCallOnReadonlyValueField
            var parser = _provider.GetFormat(typeof(IHttpBodyParser)) as IHttpBodyParser;

            if (parser == null)
            {
                throw new FormatException($"无法获取{nameof(IHttpBodyParser)}");
            }
            Url = url.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped);
            if (string.IsNullOrEmpty(Url) == false && Url[Url.Length - 1] == '/' && Url.Length - url.OriginalString.Length == 1)
            {
                Url = url.OriginalString;
            }
            _UrlEncodedBuilder.Clear(url.Query);
            Headers     = new List <KeyValuePair <string, string> >();
            HeaderNames = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            request.OnParamsExtracting();


            List <KeyValuePair <string, object> > bodyparams;

            FindParams(request, out bodyparams);

            if (_provider.IsUndefined == false && HeaderNames.Contains("Content-Type") == false)
            {
                AddHeader("Content-Type", _provider.ToString());
            }
            if (request.Headers.AutoAddDefaultHeaders)
            {
                if (HeaderNames.Contains("Accept") == false)
                {
                    AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                }
                if (HeaderNames.Contains("Accept-Encoding") == false)
                {
                    AddHeader("Accept-Encoding", "gzip, deflate, sdch");
                }
                if (HeaderNames.Contains("Accept-Language") == false)
                {
                    AddHeader("Accept-Language", "zh-CN,zh;q=0.8");
                }
                if (HeaderNames.Contains("Cache-Control") == false)
                {
                    AddHeader("Cache-Control", "max-age=0");
                }
                if (HeaderNames.Contains("User-Agent") == false)
                {
                    AddHeader("User-Agent", HttpHeaders.DefaultUserAgent);
                }
                if (HeaderNames.Contains("Connection") == false)
                {
                    AddHeader("Connection", "Keep-Alive");
                }
            }
            Body = request.Body._customConent ?? parser.Serialize(null, bodyparams, _provider);
            request.OnParamsExtracted();
            var query = _UrlEncodedBuilder.ToString();

            if (query.Length == 0)
            {
                Url += url.Fragment;
            }
            else if (query[0] == '?')
            {
                Url += query + url.Fragment;
            }
            else
            {
                Url += "?" + query + url.Fragment;
            }

            if (Method == null)
            {
                Method = Body?.Length > 0 ? "POST" : "GET";
            }

            if (request.Headers.AutoAddDefaultHeaders && request.Headers.Contains("Host") == false)
            {
                AddHeader("Host", new[] { url.Host });
            }
            if (request.CookieMode == HttpCookieMode.None)
            {
                return;
            }

            switch (request.CookieMode)
            {
            case HttpCookieMode.ApplicationCache:
                Cookies = HttpRequest.LocalCookies;
                break;

            case HttpCookieMode.UserCustom:
                Cookies = request.Cookies;
                break;

            case HttpCookieMode.CustomOrCache:
                Cookies = request.Cookies;
                var cookies = HttpRequest.LocalCookies?.GetCookies(Host);     //加载全局缓存Cookie
                if (cookies != null)
                {
                    Cookies.Add(cookies);
                }
                break;

            default:
                break;
            }
        }