Пример #1
0
        private static HttpGetCfg CreateDefaultHttpGetCfg()
        {
            var httpCfg = new HttpGetCfg
            {
                ReTryCount        = 3,
                IsFormContentType = false,
            };

            return(httpCfg);
        }
Пример #2
0
        public static T HttpGet <T>(this string url, Dictionary <string, object> getParams, HttpGetCfg httpCfg = null)
        {
            string resultStr = url.HttpGet(getParams, httpCfg);

            var result = JsonConvert.DeserializeObject <T>(resultStr);

            return(result);
        }
Пример #3
0
        public static string HttpGet(this string url, Dictionary <string, object> getParams, HttpGetCfg httpCfg = null)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new FException("url不能为空");
            }
            if (getParams == null || !getParams.Any())
            {
                throw new FException("getParams不能为空");
            }

            if (httpCfg == null)
            {
                httpCfg = CreateDefaultHttpGetCfg();
            }
            else if (httpCfg.ReTryCount <= 0)
            {
                httpCfg.ReTryCount = 1;//至少执行一次
            }

            var restRequest = new RestRequest(Method.GET);

            restRequest.Timeout = 10 * 1000;//连接超时设置为10秒
            restRequest.AddHeader("Accept", "*/*");

            if (httpCfg.IsFormContentType)
            {
                string contentType = GetContentType(ContentType.Form);
                restRequest.AddHeader("Content-Type", contentType);
            }

            foreach (var param in getParams)
            {
                restRequest.AddParameter(param.Key, param.Value);
            }

            //如果是网络连接异常,那么重试
            IRestResponse restResponse = null;

            CallHelper.ReTryRun(reTryCount: httpCfg.ReTryCount, reTryAction: () =>
            {
                restResponse         = new RestClient(url).ExecuteAsync(restRequest).Result;
                bool hasNetWorkError = restResponse.ErrorException is System.Net.WebException;
                bool isReTrySuc      = !hasNetWorkError;
                return(isReTrySuc);
            }, remark: "HttpGet");

            //响应状态码是否表示成功 OK(200)
            if (!restResponse.IsSuccessful)
            {
                var errSb = new StringBuilder();
                errSb.AppendLine($"{url}接口异常");
                errSb.AppendLine($"Content:{restResponse.Content}");
                errSb.AppendLine($"StatusCode:{restResponse.StatusCode}");
                errSb.AppendLine($"ResponseStatus:{restResponse.ResponseStatus}");
                errSb.AppendLine($"ErrorMessage:{restResponse.ErrorMessage}");

                throw new Exception(errSb.ToString(), restResponse.ErrorException);
            }

            return(restResponse.Content);
        }