Exemplo n.º 1
0
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod, Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            ConfigureHttp(request, http);

            var asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> response_cb = r => ProcessResponse(request, r, asyncHandle, callback);

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = response_cb;

                response_cb = resp => ctx.Post(s => cb(resp), null);
            }

            asyncHandle.WebRequest = getWebRequest(http, response_cb, httpMethod);
            return(asyncHandle);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Executes the request and callback asynchronously, authenticating if needed
        /// </summary>
        /// <param name="request">Request to be executed</param>
        /// <param name="callback">Callback function to be executed upon completion providing access to the async handle.</param>
        public virtual RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action <RestResponse, RestRequestAsyncHandle> callback)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            ConfigureHttp(request, http);

            HttpWebRequest webRequest  = null;
            var            asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> response_cb = r => ProcessResponse(r, asyncHandle, callback);

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = response_cb;

                response_cb = resp => ctx.Post(s => cb(resp), null);
            }

            switch (request.Method)
            {
            case Method.GET:
                webRequest = http.GetAsync(response_cb);
                break;

            case Method.POST:
                webRequest = http.PostAsync(response_cb);
                break;

            case Method.PUT:
                webRequest = http.PutAsync(response_cb);
                break;

            case Method.DELETE:
                webRequest = http.DeleteAsync(response_cb);
                break;

            case Method.HEAD:
                webRequest = http.HeadAsync(response_cb);
                break;

            case Method.OPTIONS:
                webRequest = http.OptionsAsync(response_cb);
                break;

            case Method.PATCH:
                webRequest = http.PatchAsync(response_cb);
                break;
            }

            asyncHandle.WebRequest = webRequest;
            return(asyncHandle);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Executes the request and returns a response, authenticating if needed
        /// </summary>
        /// <param name="request">Request to be executed</param>
        /// <returns>RestResponse</returns>
        public virtual IRestResponse Execute(IRestRequest request)
        {
            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            IRestResponse response = new RestResponse();

            try
            {
                response         = GetResponse(request);
                response.Request = request;
                response.Request.IncreaseNumAttempts();
            }
            catch (Exception ex)
            {
                response.ResponseStatus = ResponseStatus.Error;
                response.ErrorMessage   = ex.Message;
                response.ErrorException = ex;
            }

            return(response);
        }
Exemplo n.º 4
0
        private IRestResponse Execute(IRestRequest request, string httpMethod, Func <IHttp, string, HttpResponse> getResponse)
        {
            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            IRestResponse response = new RestResponse();

            try
            {
                var http = HttpFactory.Create();

                ConfigureHttp(request, http);
                ConfigureProxy(http);

                response         = ConvertToRestResponse(request, getResponse(http, httpMethod));
                response.Request = request;
                response.Request.IncreaseNumAttempts();
            }
            catch (Exception ex)
            {
                response.ResponseStatus = ResponseStatus.Error;
                response.ErrorMessage   = ex.Message;
                response.ErrorException = ex;
            }

            return(response);
        }
Exemplo n.º 5
0
 public void AddHandler(string contentType, IDeserializer deserializer)
 {
     ContentHandlers[contentType] = deserializer;
     if (contentType != "*")
     {
         AcceptTypes.Add(contentType);
         string value = string.Join(", ", AcceptTypes.ToArray());
         this.RemoveDefaultParameter("Accept");
         this.AddDefaultParameter("Accept", value, ParameterType.HttpHeader);
     }
 }
Exemplo n.º 6
0
 /// <summary>
 /// Registers a content handler to process response content
 /// </summary>
 /// <param name="contentType">MIME content type of the response content</param>
 /// <param name="deserializer">Deserializer to use to process content</param>
 public void AddHandler(string contentType, IDeserializer deserializer)
 {
     ContentHandlers[contentType] = deserializer;
     if (contentType != "*")
     {
         AcceptTypes.Add(contentType);
         // add Accept header based on registered deserializers
         var accepts = string.Join(", ", AcceptTypes.ToArray());
         this.RemoveDefaultParameter("Accept");
         this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Registers a content handler to process response content
        /// </summary>
        /// <param name="contentType">MIME content type of the response content</param>
        /// <param name="deserializer">Deserializer to use to process content</param>
        public void AddHandler(string contentType, IDeserializer deserializer)
        {
            this.ContentHandlers[contentType] = deserializer;

            if (contentType != "*" && !structuredSyntaxSuffixWildcardRegex.IsMatch(contentType))
            {
                this.AcceptTypes.Add(contentType);
                // add Accept header based on registered deserializers
                var accepts = string.Join(", ", AcceptTypes.ToArray());

                this.RemoveDefaultParameter("Accept");
                this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        ///     Registers a content handler to process response content
        /// </summary>
        /// <param name="contentType">MIME content type of the response content</param>
        /// <param name="deserializer">Deserializer to use to process content</param>
        public void AddHandler(string contentType, IDeserializer deserializer)
        {
            ContentHandlers[contentType] = deserializer;

            if (contentType == "*" || IsWildcardStructuredSuffixSyntax(contentType))
            {
                return;
            }

            AcceptTypes.Add(contentType);
            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            this.RemoveDefaultParameter("Accept");
            this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);
        }
        /// <summary>
        /// Executes the request and callback asynchronously, authenticating if needed
        /// </summary>
        /// <param name="request">Request to be executed</param>
        /// <param name="callback">Callback function to be executed upon completion</param>
        public virtual void ExecuteAsync(RestRequest request, Action <RestResponse> callback)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            ConfigureHttp(request, http);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            switch (request.Method)
            {
            case Method.GET:
                http.GetAsync(r => ProcessResponse(r, callback));
                break;

            case Method.POST:
                http.PostAsync(r => ProcessResponse(r, callback));
                break;

            case Method.PUT:
                http.PutAsync(r => ProcessResponse(r, callback));
                break;

            case Method.DELETE:
                http.DeleteAsync(r => ProcessResponse(r, callback));
                break;

            case Method.HEAD:
                http.HeadAsync(r => ProcessResponse(r, callback));
                break;

            case Method.OPTIONS:
                http.OptionsAsync(r => ProcessResponse(r, callback));
                break;
            }
        }
Exemplo n.º 10
0
        private void ConfigureHttp(IRestRequest request, IHttp http)
        {
            http.Encoding = Encoding;
            http.AlwaysMultipartFormData = request.AlwaysMultipartFormData;
            http.UseDefaultCredentials   = request.UseDefaultCredentials;
            http.ResponseWriter          = request.ResponseWriter;
            http.CookieContainer         = CookieContainer;


            // move RestClient.DefaultParameters into Request.Parameters
            foreach (var p in DefaultParameters)
            {
                if (request.Parameters.Any(p2 => p2.Name == p.Name && p2.Type == p.Type))
                {
                    continue;
                }

                request.AddParameter(p);
            }

            // Add Accept header based on registered deserializers if none has been set by the caller.
            if (request.Parameters.All(p2 => p2.Name.ToLowerInvariant() != "accept"))
            {
                var accepts = string.Join(", ", AcceptTypes.ToArray());

                request.AddParameter("Accept", accepts, ParameterType.HttpHeader);
            }

            http.Url             = BuildUri(request);
            http.PreAuthenticate = PreAuthenticate;

            var userAgent = UserAgent ?? http.UserAgent;

            http.UserAgent = userAgent.HasValue()
                ? userAgent
                : "RestSharp/" + version;

            var timeout = request.Timeout > 0
                ? request.Timeout
                : Timeout;

            if (timeout > 0)
            {
                http.Timeout = timeout;
            }

            var readWriteTimeout = request.ReadWriteTimeout > 0
                ? request.ReadWriteTimeout
                : ReadWriteTimeout;

            if (readWriteTimeout > 0)
            {
                http.ReadWriteTimeout = readWriteTimeout;
            }

            http.FollowRedirects = FollowRedirects;

            if (ClientCertificates != null)
            {
                http.ClientCertificates = ClientCertificates;
            }

            http.MaxRedirects = MaxRedirects;
            http.CachePolicy  = CachePolicy;
            http.Pipelined    = Pipelined;

            if (request.Credentials != null)
            {
                http.Credentials = request.Credentials;
            }

            var headers = from p in request.Parameters
                          where p.Type == ParameterType.HttpHeader
                          select new HttpHeader
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (var header in headers)
            {
                http.Headers.Add(header);
            }

            var cookies = from p in request.Parameters
                          where p.Type == ParameterType.Cookie
                          select new HttpCookie
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (var cookie in cookies)
            {
                http.Cookies.Add(cookie);
            }

            var @params = from p in request.Parameters
                          where p.Type == ParameterType.GetOrPost && p.Value != null
                          select new HttpParameter
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (var parameter in @params)
            {
                http.Parameters.Add(parameter);
            }

            foreach (var file in request.Files)
            {
                http.Files.Add(new HttpFile
                {
                    Name          = file.Name,
                    ContentType   = file.ContentType,
                    Writer        = file.Writer,
                    FileName      = file.FileName,
                    ContentLength = file.ContentLength
                });
            }

            var body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);

            // Only add the body if there aren't any files to make it a multipart form request
            // If there are files, then add the body to the HTTP Parameters
            if (body != null)
            {
                http.RequestContentType = body.Name;

                if (!http.Files.Any())
                {
                    var val = body.Value;

                    if (val is byte[] bytes)
                    {
                        http.RequestBodyBytes = bytes;
                    }
                    else
                    {
                        http.RequestBody = Convert.ToString(body.Value);
                    }
                }
                else
                {
                    http.Parameters.Add(new HttpParameter
                    {
                        Name        = body.Name,
                        Value       = Convert.ToString(body.Value),
                        ContentType = body.ContentType
                    });
                }
            }
            http.Proxy = Proxy;
#if NETSTANDARD2_0
            if (http.Proxy == null)
            {
                var _ = WebRequest.DefaultWebProxy;
                WebRequest.DefaultWebProxy = null;
            }
#endif
            http.RemoteCertificateValidationCallback = RemoteCertificateValidationCallback;
        }
Exemplo n.º 11
0
        private void ConfigureHttp(IRestRequest request, IHttp http)
        {
            http.AlwaysMultipartFormData = request.AlwaysMultipartFormData;
#if !PocketPC
            http.UseDefaultCredentials = request.UseDefaultCredentials;
#endif
            http.ResponseWriter = request.ResponseWriter;
#if !PocketPC
            http.CookieContainer = CookieContainer;
#endif
            // move RestClient.DefaultParameters into Request.Parameters
            foreach (var p in DefaultParameters)
            {
                if (request.Parameters.Any(p2 => p2.Name == p.Name && p2.Type == p.Type))
                {
                    continue;
                }

                request.AddParameter(p);
            }

            // Add Accept header based on registered deserializers if none has been set by the caller.
#if PocketPC
            if (request.Parameters.All(p2 => p2.Name.ToLower() != "accept"))
#else
            if (request.Parameters.All(p2 => p2.Name.ToLowerInvariant() != "accept"))
#endif
            {
                var accepts = string.Join(", ", AcceptTypes.ToArray());
                request.AddParameter("Accept", accepts, ParameterType.HttpHeader);
            }

            http.Url             = BuildUri(request);
            http.PreAuthenticate = PreAuthenticate;

            var userAgent = UserAgent ?? http.UserAgent;
            http.UserAgent = userAgent.HasValue() ? userAgent : "RestSharp/" + version;

            var timeout = request.Timeout > 0 ? request.Timeout : Timeout;
            if (timeout > 0)
            {
                http.Timeout = timeout;
            }

            var readWriteTimeout = request.ReadWriteTimeout > 0 ? request.ReadWriteTimeout : ReadWriteTimeout;
            if (readWriteTimeout > 0)
            {
                http.ReadWriteTimeout = readWriteTimeout;
            }

#if !SILVERLIGHT
            http.FollowRedirects = FollowRedirects;
#endif
#if FRAMEWORK
            if (ClientCertificates != null)
            {
                http.ClientCertificates = ClientCertificates;
            }

            http.MaxRedirects = MaxRedirects;
#endif

            if (request.Credentials != null)
            {
                http.Credentials = request.Credentials;
            }

            var headers = from p in request.Parameters
                          where p.Type == ParameterType.HttpHeader
                          select new HttpHeader
            {
                Name  = p.Name,
                Value = p.Value.ToString()
            };

            foreach (var header in headers)
            {
                http.Headers.Add(header);
            }

            var cookies = from p in request.Parameters
                          where p.Type == ParameterType.Cookie
                          select new HttpCookie
            {
                Name  = p.Name,
                Value = p.Value.ToString()
            };

            foreach (var cookie in cookies)
            {
                http.Cookies.Add(cookie);
            }

            var @params = from p in request.Parameters
                          where p.Type == ParameterType.GetOrPost &&
                          p.Value != null
                          select new HttpParameter
            {
                Name  = p.Name,
                Value = p.Value.ToString()
            };

            foreach (var parameter in @params)
            {
                http.Parameters.Add(parameter);
            }

            foreach (var file in request.Files)
            {
                http.Files.Add(new HttpFile {
                    Name = file.Name, ContentType = file.ContentType, Writer = file.Writer, FileName = file.FileName, ContentLength = file.ContentLength
                });
            }

            var body = (from p in request.Parameters
                        where p.Type == ParameterType.RequestBody
                        select p).FirstOrDefault();

            if (body != null)
            {
                object val = body.Value;
                if (val is byte[])
                {
                    http.RequestBodyBytes = (byte[])val;
                }
                else
                {
                    http.RequestBody = body.Value.ToString();
                }
                http.RequestContentType = body.Name;
            }
#if FRAMEWORK
            ConfigureProxy(http);
#endif
        }
Exemplo n.º 12
0
        internal IHttp ConfigureHttp(IRestRequest request)
        {
            var http = Http.Create();

            http.Encoding = Encoding;
            http.AlwaysMultipartFormData = request.AlwaysMultipartFormData;
            http.UseDefaultCredentials   = request.UseDefaultCredentials;
            http.ResponseWriter          = request.ResponseWriter;
            http.CookieContainer         = CookieContainer;
            http.AutomaticDecompression  = AutomaticDecompression;
            http.WebRequestConfigurator  = WebRequestConfigurator;

            // move RestClient.DefaultParameters into Request.Parameters
            foreach (var p in DefaultParameters)
            {
                var parameterExists = request.Parameters.Any(p2 => p2.Name == p.Name && p2.Type == p.Type);

                if (AllowMultipleDefaultParametersWithSameName)
                {
                    var isMultiParameter = MultiParameterTypes.Any(pt => pt == p.Type);
                    parameterExists = !isMultiParameter && parameterExists;
                }

                if (parameterExists)
                {
                    continue;
                }

                request.AddParameter(p);
            }

            // Add Accept header based on registered deserializers if none has been set by the caller.
            if (request.Parameters.All(p2 => p2.Name.ToLowerInvariant() != "accept"))
            {
                var accepts = string.Join(", ", AcceptTypes.ToArray());

                request.AddParameter("Accept", accepts, ParameterType.HttpHeader);
            }

            http.Url             = BuildUri(request);
            http.Host            = BaseHost;
            http.PreAuthenticate = PreAuthenticate;
            http.UnsafeAuthenticatedConnectionSharing = UnsafeAuthenticatedConnectionSharing;

            var userAgent = UserAgent ?? http.UserAgent;

            http.UserAgent = userAgent.HasValue()
                ? userAgent
                : "RestSharp/" + version;

            var timeout = request.Timeout != 0
                ? request.Timeout
                : Timeout;

            if (timeout != 0)
            {
                http.Timeout = timeout;
            }

            var readWriteTimeout = request.ReadWriteTimeout != 0
                ? request.ReadWriteTimeout
                : ReadWriteTimeout;

            if (readWriteTimeout != 0)
            {
                http.ReadWriteTimeout = readWriteTimeout;
            }

            http.FollowRedirects = FollowRedirects;

            if (ClientCertificates != null)
            {
                http.ClientCertificates = ClientCertificates;
            }

            http.MaxRedirects = MaxRedirects;
            http.CachePolicy  = CachePolicy;
            http.Pipelined    = Pipelined;

            if (request.Credentials != null)
            {
                http.Credentials = request.Credentials;
            }

            if (!string.IsNullOrEmpty(ConnectionGroupName))
            {
                http.ConnectionGroupName = ConnectionGroupName;
            }

            var headers = from p in request.Parameters
                          where p.Type == ParameterType.HttpHeader
                          select new HttpHeader
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (var header in headers)
            {
                http.Headers.Add(header);
            }

            var cookies = from p in request.Parameters
                          where p.Type == ParameterType.Cookie
                          select new HttpCookie
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (var cookie in cookies)
            {
                http.Cookies.Add(cookie);
            }

            var @params = from p in request.Parameters
                          where p.Type == ParameterType.GetOrPost && p.Value != null
                          select new HttpParameter
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (var parameter in @params)
            {
                http.Parameters.Add(parameter);
            }

            foreach (var file in request.Files)
            {
                http.Files.Add(new HttpFile
                {
                    Name          = file.Name,
                    ContentType   = file.ContentType,
                    Writer        = file.Writer,
                    FileName      = file.FileName,
                    ContentLength = file.ContentLength
                });
            }

            var body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);

            // Only add the body if there aren't any files to make it a multipart form request
            // If there are files, then add the body to the HTTP Parameters
            if (body != null)
            {
                http.RequestContentType = body.Name;

                if (!http.Files.Any())
                {
                    var val = body.Value;

                    if (val is byte[] bytes)
                    {
                        http.RequestBodyBytes = bytes;
                    }
                    else
                    {
                        http.RequestBody = Convert.ToString(body.Value);
                    }
                }
                else
                {
                    http.Parameters.Add(new HttpParameter
                    {
                        Name        = body.Name,
                        Value       = Convert.ToString(body.Value),
                        ContentType = body.ContentType
                    });
                }
            }

            http.AllowedDecompressionMethods = request.AllowedDecompressionMethods;
            http.Proxy = Proxy ?? (WebRequest.DefaultWebProxy ?? HttpWebRequest.GetSystemWebProxy());
            http.RemoteCertificateValidationCallback = RemoteCertificateValidationCallback;

            return(http);
        }
Exemplo n.º 13
0
        private void ConfigureHttp(IRestRequest request, IHttp http)
        {
            http.Encoding = Encoding;
            http.AlwaysMultipartFormData = request.AlwaysMultipartFormData;
            http.UseDefaultCredentials   = request.UseDefaultCredentials;
            http.ResponseWriter          = request.ResponseWriter;
            http.CookieContainer         = CookieContainer;
            using (IEnumerator <Parameter> enumerator = DefaultParameters.GetEnumerator())
            {
                Parameter p3;
                while (enumerator.MoveNext())
                {
                    p3 = enumerator.Current;
                    if (!request.Parameters.Any((Parameter p2) => p2.Name == p3.Name && p2.Type == p3.Type))
                    {
                        request.AddParameter(p3);
                    }
                }
            }
            if (request.Parameters.All((Parameter p2) => p2.Name.ToLowerInvariant() != "accept"))
            {
                string value = string.Join(", ", AcceptTypes.ToArray());
                request.AddParameter("Accept", value, ParameterType.HttpHeader);
            }
            http.Url             = BuildUri(request);
            http.PreAuthenticate = PreAuthenticate;
            string text = UserAgent ?? http.UserAgent;

            http.UserAgent = (text.HasValue() ? text : ("RestSharp/" + version));
            int num = (request.Timeout > 0) ? request.Timeout : Timeout;

            if (num > 0)
            {
                http.Timeout = num;
            }
            int num2 = (request.ReadWriteTimeout > 0) ? request.ReadWriteTimeout : ReadWriteTimeout;

            if (num2 > 0)
            {
                http.ReadWriteTimeout = num2;
            }
            http.FollowRedirects = FollowRedirects;
            if (ClientCertificates != null)
            {
                http.ClientCertificates = ClientCertificates;
            }
            http.MaxRedirects = MaxRedirects;
            if (request.Credentials != null)
            {
                http.Credentials = request.Credentials;
            }
            IEnumerable <HttpHeader> enumerable = from p in request.Parameters
                                                  where p.Type == ParameterType.HttpHeader
                                                  select new HttpHeader
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (HttpHeader item in enumerable)
            {
                http.Headers.Add(item);
            }
            IEnumerable <HttpCookie> enumerable2 = from p in request.Parameters
                                                   where p.Type == ParameterType.Cookie
                                                   select new HttpCookie
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (HttpCookie item2 in enumerable2)
            {
                http.Cookies.Add(item2);
            }
            IEnumerable <HttpParameter> enumerable3 = from p in request.Parameters
                                                      where p.Type == ParameterType.GetOrPost && p.Value != null
                                                      select new HttpParameter
            {
                Name  = p.Name,
                Value = Convert.ToString(p.Value)
            };

            foreach (HttpParameter item3 in enumerable3)
            {
                http.Parameters.Add(item3);
            }
            foreach (FileParameter file in request.Files)
            {
                http.Files.Add(new HttpFile
                {
                    Name          = file.Name,
                    ContentType   = file.ContentType,
                    Writer        = file.Writer,
                    FileName      = file.FileName,
                    ContentLength = file.ContentLength
                });
            }
            Parameter parameter = (from p in request.Parameters
                                   where p.Type == ParameterType.RequestBody
                                   select p).FirstOrDefault();

            if (parameter != null)
            {
                http.RequestContentType = parameter.Name;
                if (!http.Files.Any())
                {
                    object value2 = parameter.Value;
                    if (value2 is byte[])
                    {
                        http.RequestBodyBytes = (byte[])value2;
                    }
                    else
                    {
                        http.RequestBody = Convert.ToString(parameter.Value);
                    }
                }
                else
                {
                    http.Parameters.Add(new HttpParameter
                    {
                        Name  = parameter.Name,
                        Value = Convert.ToString(parameter.Value)
                    });
                }
            }
            ConfigureProxy(http);
        }
        private IHttp ConfigureHttp(IRestRequest request)
        {
            var http = new Http
            {
                Encoding = Encoding,
                AlwaysMultipartFormData = request.AlwaysMultipartFormData,
                UseDefaultCredentials   = request.UseDefaultCredentials,
                ResponseWriter          = request.ResponseWriter,
                AdvancedResponseWriter  = request.AdvancedResponseWriter,
                CookieContainer         = CookieContainer,
                AutomaticDecompression  = AutomaticDecompression,
                WebRequestConfigurator  = WebRequestConfigurator,
                Encode = Encode
            };

            var requestParameters = new List <Parameter> ();

            requestParameters.AddRange(request.Parameters);

            // move RestClient.DefaultParameters into Request.Parameters
            foreach (var defaultParameter in DefaultParameters)
            {
                var parameterExists =
                    request.Parameters.Any(p =>
                                           p.Name.Equals(defaultParameter.Name, StringComparison.InvariantCultureIgnoreCase) &&
                                           p.Type == defaultParameter.Type);

                if (AllowMultipleDefaultParametersWithSameName)
                {
                    var isMultiParameter = MultiParameterTypes.Any(pt => pt == defaultParameter.Type);
                    parameterExists = !isMultiParameter && parameterExists;
                }

                if (!parameterExists)
                {
                    requestParameters.Add(defaultParameter);
                }
            }

            // Add Accept header based on registered deserializers if none has been set by the caller.
            if (requestParameters.All(
                    p => !string.Equals(p.Name, "accept", StringComparison.InvariantCultureIgnoreCase)))
            {
                var accepts = string.Join(", ", AcceptTypes.ToArray());

                requestParameters.Add(new Parameter("Accept", accepts, ParameterType.HttpHeader));
            }

            http.Url             = BuildUri(request);
            http.Host            = BaseHost;
            http.PreAuthenticate = PreAuthenticate;
            http.UnsafeAuthenticatedConnectionSharing = UnsafeAuthenticatedConnectionSharing;

            var userAgent = UserAgent ?? http.UserAgent;

            http.UserAgent = userAgent.HasValue()
                                ? userAgent
                                : "RestSharp/" + Version;

            var timeout = request.Timeout != 0
                                ? request.Timeout
                                : Timeout;

            if (timeout != 0)
            {
                http.Timeout = timeout;
            }

            var readWriteTimeout = request.ReadWriteTimeout != 0
                                ? request.ReadWriteTimeout
                                : ReadWriteTimeout;

            if (readWriteTimeout != 0)
            {
                http.ReadWriteTimeout = readWriteTimeout;
            }

            http.FollowRedirects = FollowRedirects;

            if (ClientCertificates != null)
            {
                http.ClientCertificates = ClientCertificates;
            }

            http.MaxRedirects = MaxRedirects;
            http.CachePolicy  = CachePolicy;
            http.Pipelined    = Pipelined;

            if (request.Credentials != null)
            {
                http.Credentials = request.Credentials;
            }

            if (!string.IsNullOrEmpty(ConnectionGroupName))
            {
                http.ConnectionGroupName = ConnectionGroupName;
            }

            http.Headers = requestParameters
                           .Where(p => p.Type == ParameterType.HttpHeader)
                           .Select(p => new HttpHeader {
                Name = p.Name, Value = Convert.ToString(p.Value)
            })
                           .ToList();

            http.Cookies = requestParameters
                           .Where(p => p.Type == ParameterType.Cookie)
                           .Select(p => new HttpCookie {
                Name = p.Name, Value = Convert.ToString(p.Value)
            })
                           .ToList();

            http.Parameters = requestParameters
                              .Where(p => p.Type == ParameterType.GetOrPost && p.Value != null)
                              .Select(p => new HttpParameter {
                Name = p.Name, Value = Convert.ToString(p.Value)
            })
                              .ToList();

            http.Files = request.Files.Select(file => new HttpFile
            {
                Name          = file.Name,
                ContentType   = file.ContentType,
                Writer        = file.Writer,
                FileName      = file.FileName,
                ContentLength = file.ContentLength
            }).ToList();

            http.AddBody(requestParameters, Serializers, request.XmlSerializer, request.JsonSerializer);

            http.AllowedDecompressionMethods = request.AllowedDecompressionMethods;

            var proxy = Proxy ?? WebRequest.DefaultWebProxy;

            try
            {
                if (proxy == null)
                {
                    proxy = WebRequest.GetSystemWebProxy();
                }
            }
            catch (PlatformNotSupportedException)
            {
                // Ignore platform unsupported proxy detection
            }

            http.Proxy = proxy;

            http.RemoteCertificateValidationCallback = RemoteCertificateValidationCallback;

            return(http);
        }