/// <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); }
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); }
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); }
/// <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); }
/// <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); } }
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); } }
/// <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); } }
/// <summary> /// Handles the standard filter method. /// </summary> /// <param name="filterContext"></param> public void OnException(ExceptionContext filterContext) { JsonErrorResult errorResult; if ( // has the exception already been handled? filterContext.ExceptionHandled // there gots to be an exception! || (filterContext.Exception == null) ) { // don't process it, just return return; } // if an exception type has been defined and the exception is NOT that type if (this.ExceptionType != null && this.ExceptionType != filterContext.Exception.GetType()) { return; } // if we only care about handling on ajax requests and this is NOT one... if (AjaxOnlyRequest && !filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { // ... then don't do anything. return; } // if 1 or more accept types have been specified, if (AcceptTypes != null && AcceptTypes.Length > 0) { // see that at least 1 of the types exists in both lists. if (AcceptTypes.Join(filterContext.HttpContext.Request.AcceptTypes, t => t, t => t, (t, r) => t).Count() == 0) { return; } } errorResult = JsonErrorResult.Create(IncludeException ? filterContext.Exception : null, this.Message); // set the call result to the JSON error result package filterContext.Result = new JsonResult() { Data = errorResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; // mark the exception as handled to stop further error filter handling filterContext.HttpContext.Response.StatusCode = HttpStatusCode; filterContext.ExceptionHandled = true; NotifyExceptionHandled(filterContext); }
/// <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); } }
public void AddHandler(string contentType, IDeserializer deserializer) { ContentHandlers[contentType] = deserializer; if (contentType == "*" || StructuredSyntaxSuffixWildcardRegex.IsMatch(contentType)) { return; } AcceptTypes.Add(contentType); var accepts = string.Join(", ", AcceptTypes); RemoveDefaultParameter("Accept"); AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader); }
/// <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; } }
///<summary> ///Creates a new object that is a copy of the current instance. ///</summary> /// ///<returns> ///A new object that is a copy of this instance. ///</returns> ///<filterpriority>2</filterpriority> public object Clone() { // this method was mainly created for testing. // dont use it that much... var request = new HttpRequest(); request.Method = _method; if (AcceptTypes != null) { request.AcceptTypes = new string[AcceptTypes.Length]; AcceptTypes.CopyTo(request.AcceptTypes, 0); } request._httpVersion = _httpVersion; request._queryString = _queryString; request.Uri = _uri; var buffer = new byte[_body.Length]; _body.Read(buffer, 0, (int)_body.Length); request.Body = new MemoryStream(); request.Body.Write(buffer, 0, buffer.Length); request.Body.Seek(0, SeekOrigin.Begin); request.Body.Flush(); request._headers.Clear(); foreach (string key in _headers) { string[] values = _headers.GetValues(key); if (values != null) { foreach (string value in values) { request.AddHeader(key, value); } } } Clear(); return(request); }
/// <summary> /// Will return the best matching content type OR the first given! /// </summary> /// <param name="myContentTypes"></param> /// <returns></returns> public ContentType GetBestMatchingAcceptHeader(params ContentType[] myContentTypes) { var _ListOfFoundAcceptHeaders = new List <AcceptType>(); UInt32 pos = 0; foreach (var _ContentType in myContentTypes) { var _AcceptType = new AcceptType(_ContentType.ToString(), pos++); var _Match = AcceptTypes.Find(_AType => _AType.Equals(_AcceptType)); if (_Match != null) { if (_Match.ContentType.GetMediaSubType() == "*") // this was a * and we will set the quality to lowest { _AcceptType.Quality = 0; } _ListOfFoundAcceptHeaders.Add(_AcceptType); } } _ListOfFoundAcceptHeaders.Sort(); if (!_ListOfFoundAcceptHeaders.IsNullOrEmpty()) { return(_ListOfFoundAcceptHeaders.First().ContentType); } else if (!myContentTypes.IsNullOrEmpty()) { return(myContentTypes.First()); } else { return(null); } }
public string SelectFirstMatching(IEnumerable <string> candidates) { var exact = candidates.FirstOrDefault(x => AcceptTypes.Contains(x)); return(exact ?? (AcceptsAny() ? candidates.FirstOrDefault() : null)); }
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 }
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); }
/// <summary> /// Remove all content handlers /// </summary> public void ClearHandlers() { ContentHandlers.Clear(); AcceptTypes.Clear(); }
/// <summary> /// Remove a content handler for the specified MIME content type /// </summary> /// <param name="contentType">MIME content type to remove</param> public void RemoveHandler(string contentType) { ContentHandlers.Remove(contentType); AcceptTypes.Remove(contentType); }
public bool CanConvert(FileConverterContext context) { return(TargetType == context.TargetType && AcceptTypes.Contains(context.InputType)); }
public bool AcceptsAny() { return(AcceptTypes.Contains("*/*")); }
/// <summary> /// Remove all content handlers /// </summary> public void ClearHandlers() { ContentHandlers.Clear(); AcceptTypes.Clear(); this.RemoveDefaultParameter("Accept"); }
/// <summary> /// Set the HTTP Accept header field. /// </summary> /// <param name="AcceptTypes">AcceptTypes.</param> public HTTPRequestBuilder SetAccept(AcceptTypes AcceptTypes) { this.Accept = Accept; return this; }
public bool AcceptsAny() { return(AcceptTypes.DefaultIfEmpty("*/*").Contains("*/*")); }
public bool AcceptsHtml() { return(AcceptTypes.Contains(MimeType.Html.ToString())); }
/// <summary> /// Remove a content handler for the specified MIME content type /// </summary> /// <param name="contentType">MIME content type to remove</param> public void RemoveHandler(string contentType) { ContentHandlers.Remove(contentType); AcceptTypes.Remove(contentType); this.RemoveDefaultParameter("Accept"); }
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); }
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; }
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); }