private IRestResponse DoRequest() { var client = new RestClient(HttpOption.RequestUrl); var request = new RestRequest(GetRestSharpMethod(HttpOption.Method)); var headers = HosScheduleFactory.ConvertParamsJson(HttpOption.Headers); foreach (var (key, value) in headers) { request.AddHeader(key, value.ToString()); } request.AddHeader("content-type", HttpOption.ContentType); request.Timeout = 10000; var config = ConfigurationCache.GetField<int>("Http_RequestTimeout"); if (config > 0) { request.Timeout = config * 1000; } var requestBody = string.Empty; switch (HttpOption.ContentType) { case "application/json" when HttpOption.Body != null: requestBody = HttpOption.Body.Replace("\r\n", ""); break; case "application/x-www-form-urlencoded" when HttpOption.Body != null: { var formData = HosScheduleFactory.ConvertParamsJson(HttpOption.Body); requestBody = string.Join('&', formData.Select(x => $"{x.Key}={System.Net.WebUtility.UrlEncode(x.Value.ToString())}")); if (request.Method == Method.GET && formData.Count > 0) { client.BaseUrl = new Uri($"{HttpOption.RequestUrl}?{requestBody}"); } break; } } if (request.Method != Method.GET) { request.AddParameter(HttpOption.ContentType, requestBody, ParameterType.RequestBody); } var response = client.Execute(request); return response; }
public HttpTask(ScheduleHttpOptionEntity httpOption) { if (httpOption != null) { _option = httpOption; _headers = HosScheduleFactory.ConvertParamsJson(httpOption.Headers); if (_headers.ContainsKey(HEADER_TIMEOUT) && int.TryParse(_headers[HEADER_TIMEOUT].ToString(), out int result) && result > 0) { _timeout = TimeSpan.FromSeconds(result); } else { int config = ConfigurationCache.GetField <int>("Http_RequestTimeout"); if (config > 0) { _timeout = TimeSpan.FromSeconds(config); } } string requestBody = string.Empty; string url = httpOption.RequestUrl; if (httpOption.ContentType == "application/json") { requestBody = httpOption.Body?.Replace("\r\n", ""); } else if (httpOption.ContentType == "application/x-www-form-urlencoded") { var formData = HosScheduleFactory.ConvertParamsJson(httpOption.Body); requestBody = string.Join('&', formData.Select(x => $"{x.Key}={System.Net.WebUtility.UrlEncode(x.Value.ToString())}")); if (httpOption.Method.ToLower() == "get" && formData.Count > 0) { url = $"{httpOption.RequestUrl}?{requestBody}"; } } _option.RequestUrl = url; _option.Body = requestBody; } }