C# 请求帮助类
RestSharp版(不同版本,调用上有差异,本处使用的版本是:108.0.3.0)
/// <summary>
/// HTTP请求帮助类
/// </summary>
public static class RequestHelper
{
/// <summary>
/// 默认请求超时时间(毫秒)
/// </summary>
private const int TimeOut = 15 * 1000;
#region post请求
public static T HttpPost<T>(string url, object data, Dictionary<string, string> headerDic = null, int timeOut = TimeOut, string contentType = "application/json")
{
return SerializeHelper.Deserialize<T>(HttpPost(url, data, headerDic, timeOut, contentType));
}
public static string HttpPost(string url, object data, Dictionary<string, string> headerDic = null, int timeOut = TimeOut, string contentType = "application/json")
{
HttpsDefaultSet(url);
//请求
RestRequest request = new RestRequest(url, Method.Post);
AddHeaderInfo(request, headerDic);
request.Timeout = timeOut;
request.AddHeader("Content-Type", contentType);
if (data != null)
{
if (contentType == "application/x-www-form-urlencoded")
{
request.AddStringBody(Convert.ToString(data), DataFormat.Binary);
}
else
{
request.AddStringBody(SerializeHelper.ToJson(data), DataFormat.Json);
}
}
//响应
RestResponse response;
using (var client = new RestClient())
{
response = client.Execute(request);
}
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Content;
}
throw new Exception($"HttpPost请求出错(状态码:{(int)response.StatusCode},内容:{response.Content})");
}
#endregion
#region get请求
public static T HttpGet<T>(string url, Dictionary<string, string> urlParameters = null, Dictionary<string, string> headerDic = null, string referer = null, int timeOut = TimeOut)
{
return SerializeHelper.Deserialize<T>(HttpGet(url, urlParameters, headerDic, referer, timeOut));
}
public static string HttpGet(string url, Dictionary<string, string> urlParameters = null, Dictionary<string, string> headerDic = null, string referer = null, int timeOut = TimeOut)
{
HttpsDefaultSet(url);
//请求
RestRequest request = new RestRequest(BuildQuery(url, urlParameters));
request.Timeout = timeOut;
AddHeaderInfo(request, headerDic);
if (string.IsNullOrEmpty(referer) == false)
{
request.AddHeader("referer", referer);
}
//响应
RestResponse response;
using (var client = new RestClient())
{
response = client.Execute(request);
}
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Content;
}
throw new Exception($"HttpGet请求出错(状态码:{(int)response.StatusCode},内容:{response.Content})");
}
#endregion
#region 其他辅助方法
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
/// <summary>
/// https默认设置
/// </summary>
private static void HttpsDefaultSet(string reqUrl)
{
//主要是解决https基础连接已关闭……的报错问题
if (reqUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//ServicePointManager.DefaultConnectionLimit = 200;
//System.GC.Collect();
//System.Threading.Thread.Sleep(5);
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RequestHelper.CheckValidationResult);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
}
/// <summary>
/// 添加请求头信息
/// </summary>
/// <param name="request"></param>
/// <param name="headerDic"></param>
public static void AddHeaderInfo(RestRequest request, Dictionary<string, string> headerDic)
{
if (headerDic != null)
{
foreach (var item in headerDic)
{
request.AddHeader(item.Key, item.Value);
}
}
}
/// <summary>
/// 组装Get请求参数。
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
public static string BuildQuery(string url, IDictionary<string, string> parameters)
{
string query = BuildQuery(parameters);
if (url.IndexOf("?") > -1)
{
query = "&" + query;
}
else
{
query = "?" + query;
}
return url + query;
}
/// <summary>
/// 组装Get请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
public static string BuildQuery(IDictionary<string, string> parameters)
{
StringBuilder postData = new StringBuilder();
if (parameters != null)
{
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
hasParam = true;
}
}
}
return postData.ToString();
}
#region 获取客户端IP地址
/// <summary>
/// 获取客户端IP地址
/// </summary>
/// <returns></returns>
public static string GetIP()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
if (string.IsNullOrEmpty(result))
{
return "0.0.0.0";
}
return result;
}
#endregion
#endregion
}
HttpWebRequest版
public class RequestHelper
{
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
#region post 请求
public static string HttpPost(string url, object data, Dictionary<string, string> headerDic = null, int timeOut = 1000 * 10, string contentType = "application/json")
{
try
{
string paramData = string.Empty;
HttpsDefaultSet(url);
HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
wbRequest.Method = "POST";
wbRequest.Timeout = timeOut;
wbRequest.KeepAlive = false;
AddHeaderInfo(wbRequest, headerDic);
wbRequest.ContentType = contentType;
if (data != null)
{
if (data.GetType() == typeof(String) || wbRequest.ContentType == "application/x-www-form-urlencoded")
{
paramData = Convert.ToString(data);
}
else
{
paramData = SerializeHelper.ToJson(data);
wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
}
}
using (Stream requestStream = wbRequest.GetRequestStream())
{
using (StreamWriter swrite = new StreamWriter(requestStream))
{
swrite.Write(paramData);
}
}
using (HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse())
{
using (Stream responseStream = wbResponse.GetResponseStream())
{
using (StreamReader sread = new StreamReader(responseStream))
{
return sread.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Dictionary<string, string> exMsg = new Dictionary<string, string>();
exMsg.Add("codeLocation", "RequestHelper-HttpPost");
exMsg.Add("url", url);
if (data != null)
{
exMsg.Add("data", SerializeHelper.ToJson(data));
}
if (headerDic != null && headerDic.Count > 0)
{
exMsg.Add("headerDic", SerializeHelper.ToJson(headerDic));
}
exMsg.Add("timeOut", timeOut.ToString());
WebLogHelper.Error(exMsg);
throw ex;
}
}
public static T HttpPost<T>(string url, object data, Dictionary<string, string> headerDic = null, int timeOut = 1000 * 10, string contentType = "application/json")
{
return SerializeHelper.Deserialize<T>(HttpPost(url, data, headerDic, timeOut, contentType));
}
#endregion
#region get请求
public static T HttpGet<T>(string url, Dictionary<string, string> urlParameters = null, Dictionary<string, string> headerDic = null, string referer = null, int timeOut = 1000 * 10)
{
return SerializeHelper.Deserialize<T>(HttpGet(url, urlParameters, headerDic, referer, timeOut));
}
public static string HttpGet(string url, Dictionary<string, string> urlParameters = null, Dictionary<string, string> headerDic = null, string referer = null, int timeOut = 1000 * 10)
{
try
{
HttpsDefaultSet(url);
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BuildQuery(url, urlParameters));
//GET请求
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.Referer = referer;
request.Timeout = timeOut;
request.KeepAlive = false;
AddHeaderInfo(request, headerDic);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream myResponseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")))
{
//返回内容
return myStreamReader.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Dictionary<string, string> exMsg = new Dictionary<string, string>();
exMsg.Add("codeLocation", "RequestHelper-HttpGet");
exMsg.Add("url", url);
if (urlParameters != null && urlParameters.Count > 0)
{
exMsg.Add("urlParameters", SerializeHelper.ToJson(urlParameters));
}
if (headerDic != null && headerDic.Count > 0)
{
exMsg.Add("headerDic", SerializeHelper.ToJson(headerDic));
}
exMsg.Add("referer", referer);
exMsg.Add("timeOut", timeOut.ToString());
WebLogHelper.Error(exMsg);
throw ex;
}
}
#endregion
/// <summary>
/// https默认设置
/// </summary>
private static void HttpsDefaultSet(string reqUrl)
{
//主要是解决https基础连接已关闭……的问题
if (reqUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//ServicePointManager.DefaultConnectionLimit = 200;
//System.GC.Collect();
//System.Threading.Thread.Sleep(5);
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RequestHelper.CheckValidationResult);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
}
/// <summary>
/// 添加请求头信息
/// </summary>
/// <param name="request"></param>
/// <param name="headerDic"></param>
public static void AddHeaderInfo(HttpWebRequest request, Dictionary<string, string> headerDic)
{
if (headerDic != null)
{
foreach (var item in headerDic)
{
request.Headers.Add(item.Key, item.Value);
}
}
}
/// <summary>
/// 组装Get请求参数。
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
public static string BuildQuery(string url, IDictionary<string, string> parameters)
{
string query = BuildQuery(parameters);
if (url.IndexOf("?") > -1)
{
query = "&" + query;
}
else
{
query = "?" + query;
}
return url + query;
}
/// <summary>
/// 组装Get请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
public static string BuildQuery(IDictionary<string, string> parameters)
{
StringBuilder postData = new StringBuilder();
if (parameters != null)
{
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
hasParam = true;
}
}
}
return postData.ToString();
}
#region 获取客户端IP地址
/// <summary>
/// 获取客户端IP地址
/// </summary>
/// <returns></returns>
public static string GetIP()
{
if (HttpContext.Current == null)
{
return null;
}
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
if (string.IsNullOrEmpty(result))
{
return "0.0.0.0";
}
return result;
}
#endregion
}

浙公网安备 33010602011771号