C# 请求帮助类
RestSharp版(不同版本,调用上有差异,本处使用的版本是:108.0.3.0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | /// <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版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | 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 } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构