在开发HttpRequest的Post或者其他请求的时候,偶尔会遇到响应超时的情况,这个时候不是加长超时等待时间要不就设置一个重发的机制,现在我们来说一下重发机制的代码和实现
#region 重发机制
public static T ExecuteFunc<T>(Func<T> target, int retryCount = 3, int current = 1, int sleepMilliseconds = 0)
{
try
{
LogHelper.Debug(string.Format("方法{0}请求第{1}次", target.Method, current));
return target.Invoke();
}
catch (Exception ex)
{
if (retryCount - current <= 0)
{
LogHelper.Error(string.Format("方法{1}重试请求结束,报错信息:{0}", ex.Message, target.Method));
throw;
}
if (sleepMilliseconds > 0)
{
Thread.Sleep(sleepMilliseconds);
}
}
return ExecuteFunc(target, retryCount, current + 1, sleepMilliseconds);
}
Func<T> target 使用委托的方式将请求函数进行调用,如果报错就重新发送
retryCount 重发次数
current当前发送次数
sleepMilliseconds每次重发休息时间毫秒
我的Http请求函数
/// <summary>
/// 请求返回响应报文json格式
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="type">请求类型</param>
/// <param name="jsonStr">请求报文 json格式</param>
/// <param name="headerMap">请求头</param>
/// <returns></returns>
public static String doHttpRequest(String url, HttpRequestType type, string jsonStr, Dictionary<String, String> headerMap)
{
System.Net.ServicePointManager.DefaultConnectionLimit = 50;//最大支持并发数50
String requestJson = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = GetTypeName.GetRequestTypeName(type);
req.ContentType = "application/json";
req.Accept = "application/json";
req.KeepAlive = false;
HttpWebResponse resp = null;
//设置请求头
if (headerMap != null)
{
foreach (var item in headerMap.Keys)
{
req.Headers.Add(item, headerMap[item]);
}
}
Dictionary<Object, Object> map = new Dictionary<Object, Object>();
if (GetTypeName.GetRequestTypeName(type) != "GET")
{
if (string.IsNullOrEmpty(jsonStr))
{
return "没有请求参数";
}
}
try
{
//string jsonStr = JsonConvert.SerializeObject(map);
if (!string.IsNullOrEmpty(jsonStr))
{
LogHelper.Debug(string.Format("请求Url{0},参数:{1}", url, jsonStr));
byte[] data = Encoding.UTF8.GetBytes(jsonStr);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
}
resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
requestJson = reader.ReadToEnd();
}
}
catch (Exception e)
{
LogHelper.Error(string.Format("请求Url{0}报错:{1}", url, e.Message));
throw;
}
finally
{
if (req != null)
{
req.Abort();
}
if (resp != null)
{
resp.Close();
}
}
return requestJson;
}
调用方式:
HttpUtils.ExecuteFunc<string>(() => HttpUtils.doHttpRequest(url, HttpRequestType.Post, JsonStr,null));